網站搜尋

javascript - 如果螢幕寬度小於 960 像素則執行某些操作


如果我的螢幕寬度小於960像素,如何讓 jQuery 做某些事情?下面的程式碼總是觸發第二個警示,無論我的視窗大小如何:

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

    alert('More than 960');
}

答案#1

使用 jQuery 來獲取視窗的寬度。

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

答案#2

你可能想將它與調整大小事件結合使用:

 $(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 標誌。

答案#3

我建議不要為這種事情使用 jQuery,而是使用 window.innerWidth:

if (window.innerWidth < 960) {
    doSomething();
}

答案#4

你也可以使用 JavaScript 搭配媒體查詢。

const mq = window.matchMedia( "(min-width: 960px)" );

if (mq.matches) {
       alert("window width >= 960px");
} else {
     alert("window width < 960px");
}

答案#5

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

答案#6

我建議(需要 jQuery):

/*
 * windowSize
 * call this function to get windowSize any time
 */
function windowSize() {
  windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
  windowWidth = window.innerWidth ? window.innerWidth : $(window).width();

}

//Init Function of init it wherever you like...
windowSize();

// For example, get window size on window resize
$(window).resize(function() {
  windowSize();
  console.log('width is :', windowWidth, 'Height is :', windowHeight);
  if (windowWidth < 768) {
    console.log('width is under 768px !');
  }
});

已在 CodePen 添加: http://codepen.io/moabi/pen/QNRqpY?editors=0011

然後你可以輕鬆地使用變數獲取視窗的寬度:windowWidth,和高度:windowHeight

否則,取得一個 js 函式庫:http://wicky.nillia.ms/enquire.js/

答案#7

我知道我回答這個有點晚,但我希望對有類似問題的人有所幫助。當頁面因任何原因刷新時,它也有效。

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

});});