如何找到相对定位元素的偏移量

时间:2016-07-14 15:16:19

标签: javascript html css

如果html元素的父元素具有相对定位,我无法找到它的偏移量(所谓的)。
这个jsFiddle解释了我的问题:
https://jsfiddle.net/10hexdt1/

var content = document.getElementById('content');
var canvas = document.getElementById('canvas');

// CASE 1
console.log(canvas.offsetTop,canvas.offsetLeft);

// CASE 2
content.style.position = 'relative';
console.log(canvas.offsetTop,canvas.offsetLeft);

console.log('how do i get "offsets" in second case?');
#app {
  background:yellow;
  padding:20px;
}

#content {
  height:200px;
  width:100%;
}

#canvas {
  height:100%;
  width:100%;
  background:green;
}
<div id="app">
  <h1>Problem !</h1>
  <div id="content">
    <div id="canvas">

    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

最初,画布的 offsetParent 是document.body,所有offset*属性都基于此。

执行此操作时:

content.style.position = 'relative';

... content成为画布的offsetParent。

如果您想保留相对于document.body的偏移量,请使用 getBoundingClientRect()

console.log(canvas.getBoundingClientRect().top, canvas.getBoundingClientRect().left);

var content = document.getElementById('content');
var canvas = document.getElementById('canvas');

// CASE 1
console.log(canvas.offsetTop,canvas.offsetLeft);

// CASE 2
content.style.position = 'relative';
console.log(canvas.getBoundingClientRect().top, canvas.getBoundingClientRect().left);
#app {
  background:yellow;
  padding:20px;
}

#content {
  height:200px;
  width:100%;
}

#canvas {
  height:100%;
  width:100%;
  background:green;
}
<div id="app">
  <h1>Problem !</h1>
  <div id="content">
    <div id="canvas">

    </div>
  </div>
</div>