简体   繁体   English

使用jQuery使用媒体查询检测浏览器宽度

[英]Detecting browser width with media query using jQuery

I am trying to implement a precise way of figuring out the user's browser width based on a media query. 我正在尝试实现一种基于媒体查询来确定用户浏览器宽度的精确方法。 For example, I have an element div called #check_screen initially it'll be displayed as a block element. 例如,我有一个名为#check_screen的元素div,它最初将显示为块元素。 If the browser width is < 420px, then #check_screen will have a display: none property. 如果浏览器宽度小于420px,则#check_screendisplay: none属性。 This is what I have tried so far: 到目前为止,这是我尝试过的:

HTML 的HTML

<div id='check_screen'></div>

CSS 的CSS

#check_screen{
    display: block;
}

@media only screen and (max-width: 420px){
    #check_screen{
        display: none;
    }
}

jQuery jQuery的

$(document).ready(function() {
    // run test on initial page load
    checkSize();

    // run test on resize of the window
    $(window).resize(checkSize);
});

//Function to the css rule
function checkSize(){
    if ($("#check_screen").css("display") == "none" ){
        console.log("hello");
    }
}

For some reason, it is not working correctly. 由于某种原因,它无法正常工作。 When I resize the screen to < 420px, the message is not displayed to the console. 当我将屏幕尺寸调整为<420px时,该消息不会显示到控制台。 I have also tried using the :visible jQuery selector, but that does not work either. 我也尝试过使用:visible jQuery选择器,但这也不起作用。 I am using Chrome as my browser. 我使用的是Chrome浏览器。

I think you have a syntax error: $(window).resize(checkSize); 我认为您有语法错误: $(window).resize(checkSize); should be 应该

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

That correction worked for me with no other changes. 所做的更正对我没有任何其他变化。

Assign unvisible div and set its color to black. 分配不可见的div并将其颜色设置为黑色。

If resized, change its color to green. 如果调整大小,请将其颜色更改为绿色。

Javascript would be like Javascript就像

var check = $("element").css("background-color");

if(check == "black" {
}

else if...

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM