简体   繁体   中英

On load, jump to anchor within a div

Let's say I have the following page:

<html>
<body>
<div id='foo' style='scroll:auto;height:400px'>
      // content, content, content...
      <div id='bar'></div>
      // content, content, content...
</div>
</body>
</html>

What jQuery (or vanilla Javascript) can I use so that when the page loads, it jumps to #bar only within the div#foo (and not the entire page)? I don't need a fancy animation or scrolling, I just want #bar to be at the top of the div on page load.

jQuery solution (assumes all elements are positioned somehow)

$('#foo').scrollTop($('#bar').position().top);

EDIT

Side note: Make sure you set padding-top on bar and not margin-top if you want to put some space between foo and bar once its scrolled.

EDIT DOM Solution (works whether elements have been positioned or not, see @cobbals answer for a jQuery equivalent):

document.getElementById('foo').scrollTop += document.getElementById('bar').offsetTop - document.getElementById('foo').offsetTop
$(document).ready(function() {
   $("#foo").scrollTop($("#foo #bar").position().top);
})

long and unwieldily, there is probably a way to shorten it, but it gets to the right place every time.

$("#foo").scrollTop($("#foo").scrollTop() +
                    $("#bar").offset().top -
                    $("#foo").offset().top);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM