offset系列与scroll系列以及scroll兼容代码
offset系列与scroll系列
为什么使用他们
如果想要直接使用width,height,top,left,获取元素的宽、高、距离顶部的距离、距离左边的距离。他的元素属性不能再css中style标签定义,只能使用内部样式在style属性中定义。
比如
<style>
div{
width:200px;
height:200px;
}
</style>
<body>
<div id="dv"></div>
<script>
console.log(document.getElementById("dv").left);//此时left在style标签中是无法获取到的
</script>
</body>
<body>
<div id="dv" style="left:10px"></div>
<script>
console.log(document.getElementById("dv").left);//此时left在style属性中可以获取到
</script>
</body>
为了解决上述问题使用offset系列或scroll系列
offset系列
offsetWidth:
获取宽度(获取到的宽度是内容的宽度+边框)
offsetHeight:
获取高度(获取到的宽度是内容的高度+边框)
offsetTop:
获取距顶部的距离(获取到的距离同offsetLeft)
offsetLeft:
获取距左边的距离(如果没有脱离文档流:获取到的是父级元素margin+父级元素padding+父级元素的border+自己的margin。如果脱离文档:获取到的是自己的left和自己的margin)
代码
<body>
<div id="father">
<div id="child" ></div>
</div>
<script>
console.log(document.getElementById("father").offsetWidth);
console.log(document.getElementById("father").offsetHeight);
console.log(document.getElementById("father").offsetTop);
console.log(document.getElementById("father").offsetLeft);
</script>
</body>
sroll系列
scrollHeight:
获取高度(获取到的是:元素内容的实际高度,如果没有内容或者内容没有超过设定的高度,获取到的就是设置的高度)
scrollWidth:获取宽度
scrollLeft:获取左边的距离
scrolTop:获取顶部的距离
代码
<script>
// scroll系列
document.getElementById("btn").onclick=function(){
console.log(document.getElementById("dv").scrollHeight);
console.log(document.getElementById("dv").scrollWidth);
};
document.getElementById("dv").onscroll=function(){//可以获取滚动条的位置
console.log(this.scrollLeft);//获取向左滚动的距离
console.log(this.scrollTop);//获取向上滚动出去的距离
};
</script>
运行的结果
scroll的兼容代码
不同的浏览器的兼容性也不一样,为了保证在不同浏览器中都有效,则需要四种写法
1.window窗口向上滚动
2.HTML页面向上滚动
3.body向上滚动
4.全部不支持获取0
代码
function getScroll() {
return{
left:window.pageXOffset||document.documentElement.scrollLeft
||document.body.scrollLeft||0,//获取横向位置(left)
top:window.pageYOffset||document.documentElement.scrollTop
||document.body.scrollTop||0 // 获取纵向位置(top)
};
}