原生js--兼容獲取窗口滾動條位置和窗口大小的方法


各個瀏覽器對獲取獲取窗口滾動條位置和窗口大小沒有提供統一的API,以下是對其封裝,解決兼容性問題

/**
 * 獲取瀏覽器視口的大小(顯示文檔的部分)
 *
 */
function getViewPortSize(){
    // 除IE8及更早的版本以外的瀏覽器
    if( window.innerWidth != null ){
        return {
            w : window.innerWidth,
            h : window.innerHeight
        }
    }
    // 標准模式下的IE
    if( document.compatMode == "css1Compat" ){
        return {
            w : document.documentElement.clientWidth,
            h : document.documentElement.clientHeight
        }
    }
    // 怪異模式下的瀏覽器
    return {
        w : document.body.clientWidth,
        h : document.body.clientHeight
    }
}

/**
 *  獲取窗口滾動條的位置
 */
function getScrollOffset(){
    // 除IE8及更早版本
    if( window.pageXOffset != null ){
        return {
            x : window.pageXOffset,
            y : window.pageYOffset
        }
    }
    // 標准模式下的IE
    if( document.compatMode == "css1Compat" ){
        return {
            x : document.documentElement.scrollLeft,
            y : document.documentElement.scrollTop
        }
    }
    // 怪異模式下的瀏覽器
    return {
        x : document.body.scrollLeft,
        y : document.body.scrollTop
    }
}


免責聲明!

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



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