我正在尝试创建一个使用JavaScript选择页面区域的小部件,但问题是当它保存X/Y
和Width/Height
时,它实际上只与该屏幕大小相关,因此,如果我们尝试在另一个用户的计算机上绘制该选择,它将会离开正确的位置。
无论用户的屏幕大小是什么,依赖什么以及如何跟踪x
和y
位置?
答案 0 :(得分:2)
obj.offsetLeft
和obj.offsetTop
将始终相对于上/左角为0,0。
window.innerWidth / 2;
window.innerHeight / 2;
elementNode.offsetWidth;
elementNode.offsetHeight;
将对象放在屏幕中间:
el = document.getElementById('my_div');
el.style.position = 'absolute';
el.style.left = Math.floor((window.innerWidth / 2) - (el.offsetWidth / 2)) + 'px';
el.style.top = Math.floor((window.innerHeight / 2) - (el.offsetHeight / 2)) + 'px';