javascript - 查找相对于窗口的 div 左侧位置
问题描述
我想找到相对于窗口的 div 左侧位置。
我正在这样做
var diff = ($('.content-wrapper').outerWidth(true) - $('.content-wrapper').outerWidth()) ;
这工作正常,但我想看看是否有更好的方法来做到这一点?
任何建议或帮助将不胜感激。
提前致谢
解决方案
您可以使用getBoundingClientRect。
function getOffsetLeft() {
var testDiv = document.getElementById("test");
document.getElementById("demo").innerHTML = testDiv.getBoundingClientRect().left;
}
html, body {
margin: 0;
}
#test {
left: 100px;
margin: 10px;
padding: 10px;
width: 300px;
position: relative;
border: 5px solid black
}
<div id="test">
<p>Click the button to get getBoundingClientRect().leftt for the test div.</p>
<p><button onclick="getOffsetLeft()">Try it</button></p>
<p>offsetLeft is: <span id="demo"></span></p>
</div>
推荐阅读
- jenkins - 使节点作为代理在舞台内运行脚本
- terminal - 在linux中按字母顺序查找目录中的第n个文件
- api-design - Restful API:url中的敏感数据
- python - 根据阈值创建用于从数据帧中删除变量(分类)的函数
- android - Excel - 适用于 Android 平板电脑的复选框等效项
- java - 如何在 Spring Boot 中使用 apache poi 对标头进行分组?
- c++ - C++ Primer 5th Edition (Stanley) - 关于练习 7-39 的问题
- json - 解析包含另一个 json 字符串的字符串 json
- django - 如何使用带有 F() 引用的外键字段的 Django Queryset update() 函数?
- mysql - 如何在flutter中从MySQL数据库中获取最后插入的记录