1. 程式人生 > >client家族 scroll家族 offset家族

client家族 scroll家族 offset家族

分析圖片
client家族(可視區域):clientWidth=content+padding (不包括border)其它一樣
clientLeft=border-left-width (邊框的寬度) 其它一樣
offset家族:offsetWidth=padding+content+border 其它一樣
offsetLeft=margin-left (當前元素距離有定位的父盒子左邊的距離)

scroll家族 :scrollWidth/scrollHeight:能夠滾動的內容的 寬度 和 高度
scrollTop=滾動條滑動和可視區域的頂部的距離

封裝scroll 封裝client
相容重要點:document.compatMode的用法:獲取頁面寬高

在Standards Mode下對於盒模型的解釋和其他的標準瀏覽器是一樣,在Quirks Mode模式下則有很大差別,而在不宣告Doctype的情況下,IE預設又是Quirks Mode。

document.compatMode正好派上用場,它有兩種可能的返回值:BackCompat和CSS1Compat。

BackCompat:標準相容模式關閉(不遵循w3c標準),瀏覽器客戶區寬度document.body.clientWidth

CSS1Compat:標準相容模式開啟(遵循w3c標準),瀏覽器客戶區寬度document.documentElement.clientWidth

封裝scroll 呼叫scroll().top

/*
* 封裝scroll函式 獲取頁面滾動的top left
* */
function scroll() {
    if(window.pageXOffset!==null){
        return {
            top:window.pageYOffset,
            left:window.pageXOffset
        }
    }else if(document.compatMode ==="CSS1Compat"){
        return {
            top:document.documentElement.scrollTop,
            left:document.documentElement.scrollLeft
        }
    }

    return  {
        top:document.body.scrollTop,
        left:document.body.scrollLeft
    }
}

封裝client client().width

//獲取螢幕的寬度高度
function client() {
    if(window.innerWidth) {
        return {//ie9 最新瀏覽器
            width: window.innerWidth,
            height: window.innerHeight
        }
    }else if(document.compatMode ==="CSS1Compat"){
            return {//w3c
                width:document.documentElement.clientWidth,
                height:document.documentElement.clientHeight
            }
        }
        return  {
            width:document.body.clientWidth,
            height:document.body.clientHeight
        }
}