基于zepto判斷mobile的橫豎屏狀態(tài)

轉(zhuǎn)自http://www.cnblogs.com/lilyimage/p/4059712.html

借用jquery mobile中的代碼,刪除了一些多余的部分,簡單的基于zepto的模塊

var CheckOrientation = (function(){
    var win = $( window ),
        get_orientation,
        last_orientation,
        initial_orientation_is_landscape,
        initial_orientation_is_default,
        portrait_map = { "0": true, "180": true },
        ww, wh, landscape_threshold;

    if(window.orientation !== undefined){
        ww = window.innerWidth || win.width();
        wh = window.innerHeight || win.height();
        landscape_threshold = 50;

        initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
        initial_orientation_is_default = portrait_map[ window.orientation ];

        // (初始是橫屏,方向是0或者180), *OR*
        // 初始是豎屏,方向是90或者-90, we
        //需要調(diào)整portrait_map
        if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) {
          portrait_map = { "-90": true, "90": true };
        }

    }
      /**
       * 判斷是橫豎屏
       * @return {[type]} [description]
       */
    function get_orientation(){
        var isPortrait = true, elem = document.documentElement;

        if ( window.orientation !== undefined ) {
           
            isPortrait = portrait_map[ window.orientation ];
        } else {
            isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
        }

        return isPortrait ? "portrait" : "landscape";
    }

    last_orientation = get_orientation();

    function handler() {
        var orientation = get_orientation();
        if ( orientation !== last_orientation ) {
            last_orientation = orientation;
            win.trigger('orientation:change',[last_orientation]);//借用zepto的trigger事件
        }
    }
    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", handler, false); 
    
    return {
        get_orientation : get_orientation
    }
})();

如何使用:

(1)CheckOrientation.get_orientation() //返回的是“portrait”:表示豎屏,返回的是“l(fā)andscape”表示橫屏

(2)$(window).on('orientation:change',function(e,type){//其中type值是portrait或者是landscape});//橫豎屏轉(zhuǎn)換的時候觸發(fā)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容