繁体   English   中英

调整大小时如何同时获得屏幕的宽度和高度?

[英]How to get screen width and height simultaniously while being resized?

我有以下脚本,该脚本可以获取屏幕的宽度/高度,但是只有在刷新页面后才能执行。

function getWidth(){
    if(self.innerWidth){
        return self.innerWidth; 
    }

    if(document.documentElement && document.documentElement.clientHeight){
        return documentElement.clientWidth; 
    }

    if(document.body){
        return document.body.clientWidth;
    }
}

我想知道是否有其他替代方法可以在发生浏览时获取屏幕宽度/高度。

正如有人提到的,您可以使用调整大小的侦听器。 这是我在自己的代码中使用的示例:

<script>
        //allow global access to vars height and width, but protect namespace
        var Frame = {width:0,height:0};
        //function to get current height and width
        function getFrameSize() {              
            Frame.height = window.innerHeight;
            Frame.width = window.innerWidth;
        } 
        //set listeners to resize automatically 
        window.addEventListener('resize', getFrameSize);
        window.addEventListener('load', getFrameSize);             
    </script>

这将保留存储在Frame.height和Frame.width中的窗口内部尺寸的实际高度和宽度,并通过在每次调整窗口大小时重新检查来使值保持最新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM