加载时,跳转到div内的锚点 [英] On load, jump to anchor within a div
问题描述
假设我有以下页面:
< html>
< body>
< div id ='foo'style ='scroll:auto; height:400px'>
//内容,内容,内容...
< div id ='bar'>< / div>
//内容,内容,内容...
< / div>
< / body>
< / html>
我可以使用哪些jQuery(或vanilla Javascript),以便在页面加载时跳转到# bar 只在div#foo 内(而不是整个页面)?我不需要花哨的动画或滚动,我只想让#bar在页面加载时位于div的顶部。
jQuery解决方案(假设所有元素都以某种方式定位)
$ b $ pre $ $'''$''。scrollTop($(' #bar')位置()顶部)。。
编辑
<注意:确保你在 bar
上设置 padding-top
,而不是 margin-如果您想在
foo
和 bar
之间放置一次空格,
编辑 DOM解决方案(适用于元素是否已定位,请参阅@cobbals回答jQuery等效项):
document.getElementById('foo')。scrollTop + = document.getElementById('bar')。offsetTop - document.getElementById('foo')。 offsetTop
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
这篇关于加载时,跳转到div内的锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!