javascript - $(element).position().top 返回错误值
问题描述
我正在研究 asp.net 项目,最近我们将 jQuery 版本从 1.11.1 升级到 3.3.1,然后我们遇到了一些奇怪的问题:
$(element).position().top
你们有什么想法可以用作position().top
JavaScript 的替代品吗?
我还发现了一些关于position().top在 jQuery 3.3.1 中返回错误值的错误。
有人可以建议替代position().top
吗?这真的很有帮助。
提前致谢。
解决方案
看一下这个例子,看看如何在纯 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)
})
推荐阅读
- javascript - 捕获异步函数中的错误并通过 jest 进行测试
- c++ - 我需要根据 timeval 删除向量元素
- android - 在 Ionic 4 中处理后退按钮的问题
- svg - 如何使用 Javascript 在圆形 SVG 内添加文本?
- python - 为什么我的箱线图没有出现在 python 中?
- git - .gitignore 不会忽略包含 .git 子目录的目录吗?
- apache - Apache SSL chrome 错误:NET::ERR_CERT_AUTHORITY_INVALID
- typescript - 泛型类的工厂方法
- mediawiki - 安装后如何启用 SyntaxHighlight 扩展?
- cpanel - 我可以将 cpanel 文件夹指向由其他注册商托管的域名吗?