判断手机横屏竖屏,切换时刷新一次页面

      有些时候我们前端需要监听用户手机横屏还是竖屏放置,  这个不难但是当我们切换横屏或者竖屏的时候,也许会涉及到刷新页面,我们不可以直接在js中写window.location.reload();  因为这可能导致页面循环不断的刷新,所以就需要用某个变量控制,但是这个变量在页面刷新的时候不可以影响它的值, 所以我在这用到了  localStorage  缓存的方法。

<script>
          window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", hengshuping, false);
            $(function(){  //页面加载时检查
                hengshuping();
            });
    
            function hengshuping() {
                if (window.orientation == 0 || window.orientation == 180) {
                        var shu=window.localStorage.getItem('name')
                        if(shu=='a'){
                                window.location.reload();
                                window.localStorage.setItem('name','b');
                        }
                        //alert('竖屏')
                        orientation = 'portrait';
                        return false;
                    }
                    else if (window.orientation == 90 || window.orientation == -90) {
                        window.localStorage.setItem('name','a');
                        //alert('横屏')
                        orientation = 'landscape';
                        return false;
                    }
                }    
    </script>

猜你喜欢

转载自blog.csdn.net/qq_42205731/article/details/82318453