DOM——js盒子模型


js盒子模型-->瀏覽器提供一些獲取盒子位置信息的屬性和方法
1、clientWidth/clientHeight
clientWidth:width+左右padding
clientHeight:height+上下padding

2、clientTop/clientLeft
clientTop:上邊框的高度
clientLeft:左邊框的寬度
不存在clientRight和clientBottom,這兩屬性的是都是undefined

3、offsetWidth/offsetHeight
offsetWidth:clientWidth+左右邊框
offsetHeight:clientHeight+上下邊框

高度不設置的話,高度會自適應,height的值就是實際內容的高度

4、scrollWidth/scrollHeight
在沒有內容溢出的情況下和clientWidth/clientHeight是一樣的
有內容的溢出情況(在每一個瀏覽器中的值不太一樣,加上overflow: hidden和不加還有少許的區別):
scrollHeight:約等於 真實內容的高度(包含溢出的內容)+上padding
scrollWidth:約等於 真實內容的寬度(包含溢出的內容)+左padding
console.log(oDiv.scrollHeight);

獲取當前瀏覽器一屏幕的寬度和高度
console.log(document.documentElement.clientWidth || document.body.clientWidth);
console.log(document.documentElement.clientHeight || document.body.clientHeight);

當前所有屏加起來的高度(當前網頁的高度)~=
console.log(document.documentElement.scrollHeight||document.body.scrollHeight);

 

5、offsetLeft/offsetTop

 

偏移量:當前盒子的外邊框距離父級參照物產生的位移

 

offsetLeft:當前元素的外邊框距離父級參照物的左偏移量

offsetTop:當前元素的外邊框距離父級參照物的上偏移量

 

  獲取curEle距離body的偏移量:{top:xxx,left:xxx}

    function offset(curEle) {
        var left = curEle.offsetLeft;
        var top = curEle.offsetTop;
        var par = curEle.offsetParent;
        while (par) {
            //在標准的IE8瀏覽器中,不需要加邊框
            //navigator.userAgent獲取當前瀏覽器所有的版本的信息
            if (navigator.userAgent.indexOf("MSIE 8.0") <= -1) {
                //條件成立代表不是IE8瀏覽器,我們加上邊框
                left += par.clientLeft;
                top += par.clientTop;
            }
            left += par.offsetLeft;
            top += par.offsetTop;
            par = par.offsetParent;
        }
        return {
            left: left,
            top: top
        };
    }

  

 

 

前面的10個盒子模型的屬性都是只讀的
6、scrollLeft/scrollTop是可讀寫的
scrollTop:當前滾動條卷去的高度
scrollLeft:當前滾動條卷去的寬度

 

回到頂部案例,圖片延遲加載案例

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM