查找相对于窗口的div左位置

时间:2019-01-09 05:11:50

标签: javascript jquery css html5 screen-orientation

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

Sample Page

我就是这样

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

这工作正常,但我想看看是否还有更好的方法?

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

预先感谢

4 个答案:

答案 0 :(得分:1)

使用getBoundingClientRect

var left = document.querySelector('div').getBoundingClientRect().left;

答案 1 :(得分:0)

使用offset()方法

var diff = $('.content-wrapper').offset().left - $(window).scrollLeft();

答案 2 :(得分:0)

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

答案 3 :(得分:0)

仅此代码就足够了

$('.content-wrapper').offset().left

我已经使用以下代码进行了测试

html, body {
  margin: 0;
}    
.content-wrapper{
            position: relative;
            left: 100px;
            width: 200px;   
            height: 200px;
            border: 1px solid black;
        }

<div style="position:relative; left: 40px; width: 500px;height:auto; border: 1px solid black;">dfgdfgdf
 <div class="content-wrapper">
 dfs sf dsfds fsdfdsf
 </div>
 </div>

我要走了,包括父母的边界。

结果是:141 [自div左为100 + parrent div边界1 + parrent div左为40]