jQuery 如果屏幕分辨率发生变化,如何在jquery中检测?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8575772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:43:30  来源:igfitidea点击:

How to detect in jquery if screen resolution changes?

jqueryscreenscreen-resolution

提问by Safran Ali

How can I make it so that each time when user changes the screen resolution size [not the browser window], the page perform a function?

我怎样才能让每次用户更改屏幕分辨率大小 [不是浏览器窗口] 时,页面执行一个功能?

回答by Nathan MacInnes

Ok, so you're using jQuery. So let's make a custom event for it.

好的,所以您正在使用 jQuery。所以让我们为它制作一个自定义事件。

(function () {
    var width = screen.width,
        height = screen.height;
    setInterval(function () {
        if (screen.width !== width || screen.height !== height) {
            width = screen.width;
            height = screen.height;
            $(window).trigger('resolutionchange');
        }
    }, 50);
}());

Now $(window).bind('resolutionchange', fn)should do what you want.

现在$(window).bind('resolutionchange', fn)应该做你想做的。

回答by Benno

$(window).resize()

$(window).resize()

http://api.jquery.com/resize/

http://api.jquery.com/resize/

$(window).resize(function() {

alert('window was resized!');

});

回答by Pierre

Try tracking screen.widthand screen.height. They will return different values when changing the screen resolution. More info here.

尝试跟踪screen.widthscreen.height。更改屏幕分辨率时,它们将返回不同的值。更多信息在这里

function doSomething(){
    if ( screen.width < 1280 ){
        console.log('Too small')
    }else{
        console.log('Nice!')
    }
}

However, as far as i knowthere are no events triggered when changing the screen resolution; Which means you cannot do this $(screen).resize(function(){/*code here*/});

但是,据我所知,更改屏幕分辨率时没有触发任何事件;这意味着你不能这样做$(screen).resize(function(){/*code here*/});

So another way to do it will be using a setTimeout()such as: [not recommended]

所以另一种方法是使用setTimeout()例如:[不推荐]

var timer,
    checkScreenSize = function(){
        if ( screen.width < 1280 ){
            console.log('Too small')
        }else{
            console.log('Nice!')
        }
        timer = setTimeout(function(){ checkScreenSize(); }, 50);
    };

checkScreenSize();

The recommendedversion will be using the requestAnimationFrame. As described hereby Paul Irish. Because if you're running the loop in a tab that's not visible, the browser won't keep it running. For better overall performance.

建议的版本将使用requestAnimationFrame。正如保罗爱尔兰在这里描述的那样。因为如果您在不可见的选项卡中运行循环,浏览器将不会让它继续运行。以获得更好的整体性能。

// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();


// usage: 
// instead of setInterval(checkScreenSize, 50) ....

(function loop(){
  requestAnimFrame(loop);
  checkScreenSize();
})();

[update]

[更新]

For those who want to implement requestAnimationFrame in Nathan's answer, there you go; A custom jQuery event that is triggered on resolution change, uses requestAnimationFrame when availablefor less memory usage:

对于那些想在Nathan 的回答中实现 requestAnimationFrame的人,你去吧;在分辨率更改触发的自定义 jQuery 事件,在可用时使用 requestAnimationFrame以减少内存使用量:

window.requestAnimFrame = (function(){
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); };
})();

var width = screen.width,
    height = screen.height,
    checkScreenSize = function () {
        if (screen.width !== width || screen.height !== height) {
            width = screen.width;
            height = screen.height;
            $(window).trigger('resolutionchange');
        }
    };

(function loop(){
  requestAnimFrame(loop);
  checkScreenSize();
})();

Usage:

用法:

$(window).bind('resolutionchange', function(){
    console.log('You have just changed your resolution!');
});

回答by Willem Mulder

Because you can only from within a specific browser-window check for changes within that same browser-window, it is not possible to know about resolution-changes of the display.

因为您只能在特定浏览器窗口内检查同一浏览器窗口内的更改,所以不可能知道显示的分辨率更改。

However, if the browser window also changes when the display resolution changes, you can catch this with a listener on the window.width and window.height.

但是,如果浏览器窗口也随着显示分辨率的变化而变化,您可以使用 window.width 和 window.height 上的侦听器来捕捉这一点。

edit: It seems we can obtain the information you want from the global 'window.screen' object. See https://developer.mozilla.org/en/DOM/window.screen.heightand https://developer.mozilla.org/en/DOM/window.screen.widthfor more information!

编辑:看来我们可以从全局“window.screen”对象中获取您想要的信息。请参阅https://developer.mozilla.org/en/DOM/window.screen.heighthttps://developer.mozilla.org/en/DOM/window.screen.width了解更多信息!

回答by Arnaud Méhat

Try this js :

试试这个js:

var width = $(window).width();
var height = $(window).height(); 
var screenTimer = null;

function detectScreen (){
    $(window).resize(function() {
      height = $(window).height(); 
      width = $(window).width(); 
        getScreen ();
    });

    function getScreen (){
        return { 'height' : getHeight (), 'width': getWidth () };
    }
    screenTimer = setInterval ( getScreen (), 50 );
}
function getHeight (){
    console.log ( 'height: ' + height);
    $('#height').text(height);
    return height;
}
function getWidth (){
    console.log ( 'width: ' + width);
    $('#width').text(width);
     return width;   
}
detectScreen ();

$('#go').click (function (){
    detectScreen ();
});

$('#stop').click (function (){
    clearInterval(screenTimer);
});

And for html :

对于 html :

<span id="stop">Stop</span> | <span id="go">Go</span>
<br>
<div>height: <span id="height"></span> px</div>
<div>width: <span id="width"></span>px </div>

回答by AlphaMale

The following function fires on window re-sizing as well as resolution change and also has a delay to avoid multiple calls while the user is re-sizing the window.

以下函数在窗口大小调整和分辨率更改时触发,并且在用户调整窗口大小时也有延迟以避免多次调用。

I've set up a fiddle for you here:

我在这里为你设置了一个小提琴:

http://jsfiddle.net/EJK5L/

http://jsfiddle.net/EJK5L/

Change your resolution and function alerts you. you can perform any function, what you want.

更改您的分辨率和功能会提醒您。你可以执行任何你想要的功能。

Hope this helps.

希望这可以帮助。