关于offsetTop与offsetHeight的区别以及使用方法

来源:互联网 发布:深圳网络诈骗案 编辑:程序博客网 时间:2024/06/05 11:54

offsetTop和offsetHeight是设置一个元素的位置和获取圆度大小经常会使用的参数,下面具体讲一下他们的区别于联系:

例如obj为html的一个元素对象,

obj.offsetTop指的是obj距离上方或者父级元素(position非static)的位置,整型,单位像素。

obj.offsetHeight指obj自身的高度,整型,单位像素。

另外,还有scrollHeight与offsetHeight的区别

offsetHeight即是自身的高度,scrollHeight是自身的高度+隐藏元素的高度(即是内层元素的offsetHeight)。

由于这几个属性都是DOM对象,都需要限定针对的是某(第几)个元素进行操作的。

测试代码如下:

<!DOCTYPE html><html><head><meta charset="utf-8" /><title>offsetTop&&offsetHeight区别</title><style>*{padding: 0px;margin: 0px;}.section1{width: 100%;height:100%;background: #eee;padding: 50px 0px;position: relative;}.box1{position: relative;width: 200px;height: 200px;text-align: center;background: lightcoral;margin: 0px auto;}.box2{position: relative;width: 200px;height: 80px;overflow: hidden;text-align: center;background: lightgreen;margin: 0px auto;}h3{line-height: 100px;}</style></head><body><div class="section1"><div class="box1" id="box1"><h3>offset...区别</h3><p id="txt1"></p></div><div class="box2" id="box2"><div style="width:50px;height:300px;background-color:#0000FF;" id="t">如果为 p 设置了 scrollTop,这些内容可能不会完全显示。</div></div></div><!--javascript方法--><script type="text/javascript">var oBox1=document.getElementById('box1');var oTxt1=document.getElementById('txt1');oTxt1.innerHTML="offsetHeight:"+oBox1.offsetHeight+" offsetTop:"+oBox1.offsetTop;var oBox2=document.getElementById('box2');oBox2.scrollTop=10;console.log('oBox2.scrollHeight:'+oBox2.scrollHeight);//300console.log('oBox2.offsetHeight:'+oBox2.offsetHeight);//80</script><!--通过jquery方法书写--><script src="js/jquery-1.11.1.min.js"></script><script type="text/javascript">$(function(){//这些属性都是DOM对象,都需要限定针对的是某(第几)个元素console.log('jqyery 方法实现');console.log('box1 offsetHeight:'+$('.box1')[0].offsetHeight);console.log('box1 offsetTop:'+$('.box1')[0].offsetTop);console.log('box2 scrollTop:'+$('.box2').scrollTop());console.log('box2 scrollHeight:'+$('.box2')[0].scrollHeight);console.log('box2 offsetHeight:'+$('.box2')[0].offsetHeight);});</script></body></html>
测试结果如下:

阅读全文
0 0
原创粉丝点击