简体   繁体   English

如何使用JavaScript检查视口是否小于特定宽度?

[英]How to check if viewport is smaller than a certain width using javascript?

I want to have a simple statement to set a variable bool to false or true. 我想要一个简单的语句来将变量bool设置为false或true。 isMobile should be set to true when the viewport is smaller then 768px and above this amount it should be set to false. 当视口小于768px时,isMobile应该设置为true,并且在此数量以上时,应该将其设置为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();
});

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(); 移动var w = $(window).width(); inside resizer() . 内部resizer() This will get the value of current dimensions of window . 这将获取window 当前尺寸的值。

See the comments 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查条件大于或小于javascript中的日期? - How to check condition for date greater than or smaller than in javascript? 如何隐藏所有小于某些像素的文本,并在以后使用Javascript将它们带回? - How to hide all text, which are smaller than certain pixel and bring them back later using Javascript? 当屏幕宽度小于屏幕宽度时,如何删除Javascript中的clone()规则 - How to remove clone() rule in Javascript when screen width is smaller than 使用JavaScript检测视口宽度是否大于Mobile Safari上的可见宽度 - Detect if the viewport width is bigger than the visible width on Mobile Safari using javascript 如何使用Javascript找到虚拟视口/屏幕宽度? - How do I find the virtual viewport/screen width using Javascript? 正文尺寸小于视口时如何设置背景颜色? - How to set a background color when body size is smaller than viewport? 获取内容的宽度,而不是使用普通JavaScript的视口 - getting width of content, not viewport using vanilla JavaScript 如何使用js检测html宽度多于视口宽度? - How to use js to detect html width more than viewport width? 使用 javascript 检查输入数字是否大于某个值 - check input number whether bigger than certain value by using javascript 使用JavaScript查询时,浏览器窗口宽度小于预期值 - Browser Window width smaller than expected when querying with JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM