如果我的屏幕宽度小于 960 像素,我如何让 jQuery 做一些事情?无论我的窗口大小如何,下面的代码总是会触发第二个警报:
if (screen.width < 960) {
    alert('Less than 960');
}
else {
    alert('More than 960');
}
如果我的屏幕宽度小于 960 像素,我如何让 jQuery 做一些事情?无论我的窗口大小如何,下面的代码总是会触发第二个警报:
if (screen.width < 960) {
    alert('Less than 960');
}
else {
    alert('More than 960');
}
使用 jQuery 获取窗口的宽度。
if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}
您可能希望将其与调整大小事件结合使用:
 $(window).resize(function() {
  if ($(window).width() < 960) {
     alert('Less than 960');
  }
 else {
    alert('More than 960');
 }
});
对于 RJ:
var eventFired = 0;
if ($(window).width() < 960) {
    alert('Less than 960');
}
else {
    alert('More than 960');
    eventFired = 1;
}
$(window).on('resize', function() {
    if (!eventFired) {
        if ($(window).width() < 960) {
            alert('Less than 960 resize');
        } else {
            alert('More than 960 resize');
        }
    }
});
我尝试了http://api.jquery.com/off/ 但没有成功,所以我使用了 eventFired 标志。
我建议不要将 jQuery 用于这样的事情并继续window.innerWidth:
if (window.innerWidth < 960) {
    doSomething();
}
您还可以使用带有 javascript 的媒体查询。
const mq = window.matchMedia( "(min-width: 960px)" );
if (mq.matches) {
       alert("window width >= 960px");
} else {
     alert("window width < 960px");
}
// Adds and removes body class depending on screen width.
function screenClass() {
    if($(window).innerWidth() > 960) {
        $('body').addClass('big-screen').removeClass('small-screen');
    } else {
        $('body').addClass('small-screen').removeClass('big-screen');
    }
}
// Fire.
screenClass();
// And recheck when window gets resized.
$(window).bind('resize',function(){
    screenClass();
});