如何计算 div 内元素的 offsetTop - 返回 null?
我有一个 div
“内容”,其中有锚点 id="one"
。
现在,我正在使用外部链接中的 onClick 事件将“内容”滚动像素距离,以将“一”带入视图,而不使页面的其余部分跳转,并且它按计划工作得很好且顺利......
onClick="document.getElementById('content').scrollTop = 400;
但我宁愿计算“one”的精确 offsetTop
距离并滚动该距离,而不是我的任意数字。
这就是我正在尝试的:
<script type="text/javascript">
<!--
var topPos = document.getElementById('one').offsetTop;
//-->
</script>
并且
onClick="document.getElementById('content').scrollTop = topPos;
with
<a id="one"></a> being how I ID the element within the content.
But topPos 返回 null!我似乎无法克服这一点。我不知道这是我糟糕的 javascript 技能(可能)还是我的 css 没有提供任何数字。如果这很重要的话,我没有使用固定定位。谁能告诉我我的明显错误?提前致谢。
I have a div
"content" with anchor id="one"
inside of it.
Right now, I am using an onClick event from an exterior link to scroll "content" by a pixel distance to bring "one" into view without making the rest of the page jump and it works nice and smooth as planned...
onClick="document.getElementById('content').scrollTop = 400;
but I would rather calculate the exact offsetTop
distance of "one" and scroll by that distance instead of my arbitrary numbers.
This is what I am trying:
<script type="text/javascript">
<!--
var topPos = document.getElementById('one').offsetTop;
//-->
</script>
and
onClick="document.getElementById('content').scrollTop = topPos;
with
<a id="one"></a> being how I ID the element within the content.
But topPos returns null! I can't seem to get past this. I don't know if it's my poor javascript skills (probably) or the fact that my css isn't providing any numbers. I am not using fixed positioning, if this matters. Can anyone tell me my glaring error? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有什么理由不使用
scrollIntoView()
?https://developer.mozilla.org/en/DOM/element.scrollIntoView
Any reason not to use
scrollIntoView()
?https://developer.mozilla.org/en/DOM/element.scrollIntoView
根据脚本所在的位置,可能是因为浏览器还没有足够的信息来检索 topPos。尝试将脚本放置在页面底部或运行它以响应页面加载事件。
或者,不用提前计算,只需让 onClick 调用一个函数来计算位置并设置滚动。
Depending on where the script is located, it may be because the browser does not yet have enough info to retrieve the topPos. Try placing the script at the bottom of the page or run it in response to a page load event.
Alternatively, instead of calculating ahead, just have onClick call a function to calculate the position and set the scroll.