首页 > 解决方案 > $(element).position().top 返回错误值

问题描述

我正在研究 asp.net 项目,最近我们将 jQuery 版本从 1.11.1 升级到 3.3.1,然后我们遇到了一些奇怪的问题:

$(element).position().top

你们有什么想法可以用作position().topJavaScript 的替代品吗?

我还发现了一些关于position().top在 jQuery 3.3.1 中返回错误值的错误。

有人可以建议替代position().top吗?这真的很有帮助。

提前致谢。

标签: javascriptjqueryhtml

解决方案


看一下这个例子,看看如何在纯 JS 中获取 TOP 属性:

// Source: https://plainjs.com/javascript/styles/get-the-position-of-an-element-relative-to-the-document-24/
function offset(el) {
    var rect = el.getBoundingClientRect(),
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}


// Get properties
var test_element = document.getElementById('relative-div'),
    position = offset(test_element);


// Display them here
document.getElementById('result').innerHTML = JSON.stringify(position, null, 2);


// Use property where you need it
console.log(position.top);
#test{
  position: fixed;
  top: 20px;
  left: 300px;
  width: 100px;
  height:100px;
  background-color: red;
}
#relative-div{
  position: relative;
  left: 30px;
  top: 20px;
}
<div id='test'>
  <div id='relative-div'>xxx</div>
</div>
<pre id='result'></pre>

正如有人建议的那样,由于异步函数可能会影响页面的行为和方面,因此可能会出现您收到的错误位置值。

另一个可能的原因可能是您需要等待整个页面加载,然后才能读取该属性。为此,请使用 $(document).ready(),如下所示:

$(document).ready(function(){
     // here
     console.log($(element).position().top)
})

推荐阅读