如果我的屏幕宽度小于960像素,我如何让jQuery做一些事情?下面的代码总是触发第二个警报,不管我的窗口大小:

if (screen.width < 960) {
    alert('Less than 960');
}
else {

    alert('More than 960');
}

当前回答

// 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();
});

其他回答

我知道现在回答这个问题有点晚了,但我希望这对有类似问题的人有所帮助。当页面因任何原因刷新时,它也可以工作。

$(document).ready(function(){

if ($(window).width() < 960 && $(window).load()) {
        $("#up").hide();
    }

    if($(window).load()){
        if ($(window).width() < 960) {
        $("#up").hide();
        }
    }

$(window).resize(function() {
    if ($(window).width() < 960 && $(window).load()) {
        $("#up").hide();
    }
    else{
        $("#up").show();
    }

    if($(window).load()){
        if ($(window).width() < 960) {
        $("#up").hide();
        }
    }
    else{
        $("#up").show();
    }

});});

不,这些都没用。你需要的就是这个!!

试试这个:

if (screen.width <= 960) {
  alert('Less than 960');
} else if (screen.width >960) {
  alert('More than 960');
}

你可能想把它和一个resize事件结合起来:

 $(window).resize(function() {
  if ($(window).width() < 960) {
     alert('Less than 960');
  }
 else {
    alert('More than 960');
 }
});

R.J。:

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

let app = document.getElementById('app') const changeColorFn = ( app, color ) => { app.setAttribute("style",`background: ${color}`) } const winSizeFn = ( winWidth, callback, app, color ) => { if (window.innerWidth < winWidth ) { callback(app, color); } } winSizeFn( '1200', changeColorFn, app, 'red' ) winSizeFn( '800', changeColorFn, app, 'green' ) winSizeFn( '500', changeColorFn, app, 'blue' ) window.addEventListener("resize", (e) => { // add winSizeFn here if you want call function on window resize }) <div id="app">My app content</div>