开发者

How to calculate offsetTop of element within div - returns null?

开发者 https://www.devze.com 2023-03-13 02:27 出处:网络
I have a div \"content\" with anchor id=\"one\" inside of it. R开发者_开发知识库ight now, I am using an onClick event from an exterior link to scroll \"content\" by a pixel distance to bring \"one\"

I have a div "content" with anchor id="one" inside of it.

R开发者_开发知识库ight 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.


Any reason not to use scrollIntoView()?

https://developer.mozilla.org/en/DOM/element.scrollIntoView


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消