这篇文章说的很详细。
https://www.cnblogs.com/agansj/p/7225256.html
为元素添加top:50%; 百分比数值的时候style.left
返回的也是空字符串。
.dialog {
width: 200px;
height: 200px;
background-color: lightsalmon;
position: absolute;
left: 50%; /* 设置50%*/
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
定位使用百分比的时候offsetLeft
也会出现问题。
获取的数值总比实际数值小
坑
这是因为这个原因,本想做一个鼠标拖拽移动的效果,通过记录元素的初始offsetLeft值实现,每次都会产生抖动。
.dialog {
width: 200px;
height: 200px;
background-color: lightsalmon;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
dialog.addEventListener('mousedown', (e) => {
e.preventDefault();
isDown = true;
// get Dialog offset
offset[0] = dialog.offsetLeft;
offset[1] = dialog.offsetTop;
console.log("offsetLeft:" + offset[0]);
console.log("style.left:" + dialog.style.left);
// mouse initial position
mouseLastPosition[0] = e.clientX;
mouseLastPosition[1] = e.clientY;
}, true);
改成具体数值
.dialog {
width: 200px;
height: 200px;
background-color: lightsalmon;
position: absolute;
left: 200px;
top: 200px;
}
因为不是写在内联属性style
里,所以style
还是获取不到。
拖动以后设置了style.left
(这里就不贴代码了,脑补一下)
但是可以发现设置了实际数值以后,offsetLeft
和style.left
没有偏差了。