首页 > 解决方案 > 查找相对于窗口的 div 左侧位置

问题描述

我想找到相对于窗口的 div 左侧位置。

示例页面

我正在这样做

 var diff = ($('.content-wrapper').outerWidth(true) - $('.content-wrapper').outerWidth()) ;

这工作正常,但我想看看是否有更好的方法来做到这一点?

任何建议或帮助将不胜感激。

提前致谢

标签: javascriptjquerycsshtmlscreen-orientation

解决方案


您可以使用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>


推荐阅读