尝试跟踪screen.width 和screen.height。更改屏幕分辨率时,它们将返回不同的值。更多信息here。
function doSomething(){
if ( screen.width < 1280 ){
console.log('Too small')
}else{
console.log('Nice!')
}
}
但是,据我所知在更改屏幕分辨率时没有触发任何事件;这意味着你不能这样做$(screen).resize(function(){/*code here*/});
所以另一种方法是使用setTimeout(),例如:[不推荐]
var timer,
checkScreenSize = function(){
if ( screen.width < 1280 ){
console.log('Too small')
}else{
console.log('Nice!')
}
timer = setTimeout(function(){ checkScreenSize(); }, 50);
};
checkScreenSize();
推荐版本将使用requestAnimationFrame。正如 Paul Irish 所描述的 here。因为如果您在不可见的选项卡中运行循环,浏览器将不会使其保持运行。为了获得更好的整体性能。
// 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();
})();
[更新]
对于那些想要在Nathan's answer 中实现 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();
})();
用法:
$(window).bind('resolutionchange', function(){
console.log('You have just changed your resolution!');
});