Do something if screen width is less than 960 px

2019-01-02 16:35发布

How can I make jQuery do something if my screen width is less than 960 pixels? The code below always fires the 2nd alert, regardless of my window size:

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

    alert('More than 960');
}

标签: jquery
10条回答
看风景的人
2楼-- · 2019-01-02 17:11

Use jQuery to get the width of the window.

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}
查看更多
浪荡孟婆
3楼-- · 2019-01-02 17:17

Try this code

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

   if ($(window).width() < 960) {
     alert('width is less than 960px');
    }
    else {
     alert('More than 960');
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

查看更多
其实,你不懂
4楼-- · 2019-01-02 17:22
// 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();
});
查看更多
忆尘夕之涩
5楼-- · 2019-01-02 17:23

I recommend to not use jQuery for such thing and proceed with window.innerWidth:

if (window.innerWidth < 960) {
    doSomething();
}
查看更多
浮光初槿花落
6楼-- · 2019-01-02 17:26

use

$(window).width()

or

$(document).width()

or

$('body').width()
查看更多
冷夜・残月
7楼-- · 2019-01-02 17:27

You can also use a media query with javascript.

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

if (mq.matches) {
       alert("window width >= 960px");
} else {
     alert("window width < 960px");
}
查看更多
登录 后发表回答