最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to check if viewport is smaller than a certain width using javascript? - Stack Overflow

programmeradmin1浏览0评论

I want to have a simple statement to set a variable bool to false or true. isMobile should be set to true when the viewport is smaller then 768px and above this amount it should be set to false.

I don't know why the following code does nothing. Also there is no error in the console log.

var w = $(window).width();
var isMobile = false;

function resizer() {
    if (w < 768) {
        console.log("resize");
        isMobile = true;
    } else {
        isMobile = false;
    }
}

$(window).resize(function() {
    resizer();
});

I want to have a simple statement to set a variable bool to false or true. isMobile should be set to true when the viewport is smaller then 768px and above this amount it should be set to false.

I don't know why the following code does nothing. Also there is no error in the console log.

var w = $(window).width();
var isMobile = false;

function resizer() {
    if (w < 768) {
        console.log("resize");
        isMobile = true;
    } else {
        isMobile = false;
    }
}

$(window).resize(function() {
    resizer();
});
Share Improve this question edited Jul 6, 2015 at 14:56 stevenw00 1,1561 gold badge13 silver badges22 bronze badges asked Jul 6, 2015 at 14:32 CaspertCaspert 4,38316 gold badges68 silver badges111 bronze badges 1
  • While I don't know what happens when isMobile is toggled, you can probably achieve what you're ultimately trying to do with a simple media query without having to use JavaScript and/or jQuery. – TylerH Commented Jul 6, 2015 at 14:53
Add a ment  | 

3 Answers 3

Reset to default 5

Because you don't measure the width on every resize. Try this way:

var isMobile = false;

function resizer() {
    var w = $(window).width();
    if (w < 768) {
        console.log("resize");
        isMobile = true;
    } else { 
        isMobile = false;
    }
}

$(window).on('load resize', function(){ 
    resizer();
});

Move var w = $(window).width(); inside resizer(). This will get the value of current dimensions of window.

See the ments inline in the code.

var isMobile = false;

function resizer() {
    var w = $(window).width();
    // Move this inside resize handler

    if (w < 768) {
        console.log("resize");
        isMobile = true;
    } else {
        isMobile = false;
    }
}

$(window).resize(function() {
    resizer();
}).trigger('resize');
// ^^^^^^^^^^^^^^^^^^
// 
// Trigger event on page load

you can use these ways:

  • Method 1: Check if the user is on a mobile device

const isMobile = /Android/i.test(navigator.userAgent);

  • Method 2: Check if the screen width is less than 680 pixels

const isMobileWidth = window.innerWidth < 680;

发布评论

评论列表(0)

  1. 暂无评论