开发者

Chrome can't find offsetTop

开发者 https://www.devze.com 2023-03-08 01:56 出处:网络
style.topoffsetTop in chrome is \'object DOM Win开发者_Python百科dow\', it doesn\'t give a integer, why.

style.top offsetTop in chrome is 'object DOM Win开发者_Python百科dow', it doesn't give a integer, why. I google such issue but seems I am the only one having such a problem.

They works well in firefox. How to get an element's offsetTop in Chrome.

code:

<input type="button"id='test' value="clickme"/>
<script>
document.getElementById('test').addEventListener('click',function(){
    alert(this.offsetTop);
    top = this.offsetTop;
    alert(top);
},true)
</script>

Well, it's very interesting, it works in the alert function but can't be stored.


Because window.top already is a built-in property in the browsers. See here: https://developer.mozilla.org/en/DOM/window.top

This property is read-only (see here):

readonly attribute WindowProxy top;

which means that the assignment top = this.offsetTop doesn't do anything.

This is a classic case of an issue that arises because of global namespace pollution. Don't do it. Instead, declare your variables locally:

document.getElementById('test').addEventListener('click', function() {
    var top = this.offsetTop;
    alert(top);
}, true);
0

精彩评论

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

关注公众号