On load, jump to anchor within a div

烈酒焚心 提交于 2019-12-06 06:29:35

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

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);
$(document).ready(function() {
   $("#foo").scrollTop($("#foo #bar").position().top);
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!