龙空技术网

用js——如何获取元素的位置?

切图网阿明 1021

前言:

现时咱们对“js实现定位到页面位置”可能比较珍视,看官们都想要了解一些“js实现定位到页面位置”的相关资讯。那么小编也在网上汇集了一些有关“js实现定位到页面位置””的相关文章,希望小伙伴们能喜欢,各位老铁们一起来学习一下吧!

在做前端项目时,切图的时候,由于边边距距特别多,需要计算有相当麻烦,但我们又不要那么弄清每个元素的位置。这时候,我们可以获取某个元素在页面的位置,去比较精准的调整此元素位置。

在用js获取元素的位置之前,我的明白,元素在页面的位置的计算公式,如下:

元素在页面的位置=此元素相对浏览器视窗的位置+浏览器滚动条的值

首先用getBoundingClientRect()方法来获得某个元素相对浏览器视窗的位置 {这个方法返回的是一个对象,即Object,该对象具有4个属性:top,left,right,bottom }。我们直接用一个代码事例来说明怎么用,如下:

<html >

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Demo</title>

</head>

<body style="width:2000px; height:1000px;">

<div id="demo" style="position:absolute; left:518px; right:100px; width:500px; height:500px;

background:#CC0000; top: 114px;">Demo为了方便就直接用绝对定位的元素</div>

</body>

</html>

<script>

document.getElementById('demo').onclick=function (){

if (document.documentElement.getBoundingClientRect) {

alert("left:"+this.getBoundingClientRect().left)

alert("top:"+this.getBoundingClientRect().top)

alert("right:"+this.getBoundingClientRect().right)

alert("bottom:"+this.getBoundingClientRect().bottom)

var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;

var Y = this.getBoundingClientRect().top+document.documentElement.scrollTop;

alert("Demo的位置是X:"+X+";Y:"+Y)

}

}

</script>

标签: #js实现定位到页面位置