JavaScript-怎么获取DOM元素的位置?
直截了当说吧,就是使用Element.getBoundingClientRect()
方法返回元素的大小及其相对于视口的位置
可以获取left,top,bottom,right,width,height
该函数支持大部分浏览器,从早期的IE便开始支持使用;IE能够获取left,top,bottom,right;而现在大部分浏览器都支持获取width,height.
var box = document.getElementById(“box”);
var pos = box.getBoundingClientRect();
box.innerHTML = “top:”+pos.top +
“left:”+pos.left +
“bottom:”+pos.bottom +
“right:”+pos.right +
“width:”+pos.width +
“height:”+pos.height
var pos = box.getBoundingClientRect();
box.innerHTML = “top:”+pos.top +
“left:”+pos.left +
“bottom:”+pos.bottom +
“right:”+pos.right +
“width:”+pos.width +
“height:”+pos.height
快捷登陆