[英]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)? 我可以使用什么jQuery(或vanilla Javascript),以便在页面加载时,它仅在div#foo (而不是整个页面) 内跳转到#bar? I don't need a fancy animation or scrolling, I just want #bar to be at the top of the div on page load.
我不需要花哨的动画或滚动,我只是希望#bar在页面加载时位于div的顶部。
jQuery solution (assumes all elements are positioned somehow) jQuery解决方案(假设所有元素都以某种方式定位)
$('#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. 旁注:如果要在
foo
和bar
之间放置一些空格,请确保在bar
上设置padding-top
而不是margin-top
。
EDIT DOM Solution (works whether elements have been positioned or not, see @cobbals answer for a jQuery equivalent): 编辑 DOM解决方案(无论元素是否已定位,请参阅@cobbals的jQuery等效答案):
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.