JS操作html元素中的offset
2019-08-01 本文已影响74人
追逐_chase

我们在开发中有时会遇到获取元素的width
和height
等样式
<body>
<div id="dv1">
<div id="dv2"></div>
</div>
<input type="button" value="显示效果" id="btn" />
</body>
<script>
var dv1 = document.getElementById("dv1");
//红色div的宽和高
dv1.onclick = function () {
//在style标签中设置的样式属性获取不到
//style属性中设置的样式属性是可以获取到的
//获取元素的样式,下面的方式废了
console.log(this.style.width);
console.log(this.style.height);
};
</script>


在
style标签
中设置的样式属性获取不到
style属性
中设置的样式属性是可以获取到的
那么如何获取到 width 和height呢? offset属性可以获取
在标准流的情况下
<script>
var dv1 = document.getElementById("dv1");
//红色div的宽和高
my$("btn").onclick = function () {
//以后获取元素的宽和高,应该使用offset系列来获取
/*
*
* offsetWidth:获取元素的宽
* offsetHeight:获取元素的高
* offsetLeft:获取元素距离左边位置的值
* offsetTop:获取元素距离上面位置的值
*
* */
console.log( "宽度:"+dv1.offsetWidth);
console.log( "高度 "+ dv1.offsetHeight);
console.log( "距离左边的距离:"+ dv1.offsetLeft);
console.log("距离顶部的距离:"+ dv1.offsetTop);
/**
*/
};
</script>

上面例子的布局,只是给父级元素添加了
margin-left padding-left border

<script>
var dv1 = document.getElementById("dv1");
//红色div的宽和高
my$("btn").onclick = function () {
console.log( "宽度:"+ my$("dv2").offsetWidth);
console.log( "高度 "+ my$("dv2").offsetHeight);
console.log( "距离左边的距离:"+ my$("dv2").offsetLeft);
console.log("距离顶部的距离:"+ my$("dv2").offsetTop);
/**
*/
};
</script>

有次可以得出 在标准流的情况下 子元素的
offsetLeft
= 父元素的margin-left
+padding-left
+border-left
+ 自身元素的margin-left
同理offsetTop
也是如此
定位的情况下
- 不管父级盒子有没有定位,自己元素的
offsetLeft
= 自身的margin-left
+ 自己定位的left
- 如果父级盒子没有定位,那么子元素是相对 祖先元素的
left和margin-left


- 父级元素定位

<script>
var dv1 = document.getElementById("dv1");
//红色div的宽和高
my$("btn").onclick = function () {
console.log( "宽度:"+ my$("dv2").offsetWidth);
console.log( "高度 "+ my$("dv2").offsetHeight);
console.log( "距离左边的距离:"+ my$("dv2").offsetLeft);
console.log("距离顶部的距离:"+ my$("dv2").offsetTop);
};
</script>