开发者

Show/hide div shows the bottom of the exposed div

开发者 https://www.devze.com 2023-03-26 11:38 出处:网络
I have a page with two divs, one hidden and one displayed. When I click on a link at the bottom of the page, I want the hidden div to display and the displayed div to be hidden. It works fine, but if

I have a page with two divs, one hidden and one displayed. When I click on a link at the bottom of the page, I want the hidden div to display and the displayed div to be hidden. It works fine, but if the browser height is small (e.g., on a mobile device) the user sees the div that gets displayed scrolled all the way to the bottom.

Here is the page:

<script type="text/javascript">
function display()
{
  document.getElementById('div2').style.display="block";
  document.getElementById('div1').style.display="none";
}
</script>

<!-- Start of content -->
  <div id="div1" style="display:block">
    <h2>This is shown at the beginning</h2>
    <p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p>
    <p>Hello</p><p>Hello</p><p>Hello</p>
    <a rel="external" href="bogus.tar.gz" onclick="display(); return true">Click here</a>
  </div>

  <div id="div2" style="display:none">
  &开发者_运维问答lt;h2>This is shown later</h2>
    <p>Goodbye</p><p>Goodbye</p><p>Goodbye</p><p>Goodbye</p><p>Goodbye</p><p>Goodbye</p>
    <p>Goodbye</p><p>Goodbye</p><p>Goodbye</p>
  </div>

If I put the link at the top of the page, the problem goes away, but the flow of the page demands that the link be at the bottom of the page.

So how can I get the browser to show the top of the div once it gets displayed.


window.scrollTo(x, y)

If you want to scroll the page to the top use

window.scrollTo(0, 0)

Otherwise, change the second parameter.


hide the div1 before displaying the div2.

If it does not run, use a scrollto javascript (based on displayed div) call to fix the issue


document.getElementById('div2').scrollTop=0
0

精彩评论

暂无评论...
验证码 换一张
取 消