通过屏幕宽度检测和更改不起作用

时间:2017-11-15 22:02:42

标签: javascript jquery html screen-resolution

因此,如果屏幕尺寸小于960 px,我会检查Do something if screen width is less than 960 px以了解如何执行某些操作。但是,它对我不起作用。他们的答案是:

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

我尝试了它确实有效。我还有一个alert告诉我屏幕大小;

var size = $(window).width();
alert(size);

这很有效,但事实并非如此:

if (size < 1200) {
    $("#mobileVersionDetected").css("display", "block");
}
else {
    $("#mobileVersionDetected").css("display", "none");
}

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

如果我将$(window).width()添加到实际的if function而不是使用variable,那就可以了。

答案 1 :(得分:0)

试试这个:

if (size < 1200) {
    $('#mobileVersionDetected').attr("style", "display: block");
}
else {
    $('#mobileVersionDetected').attr("style", "display: none");
}

答案 2 :(得分:0)

要回复@charlietfl,这正是 CSS Media Queries 的用途。它们消除了对脚本的需求,并且效率更高。

    /* Baseline styles applied initially: */
    body { background-color: #b200ff; /* purple */ }

    p    { 
      border:1px solid black; 
      background: white; 
      padding:5px; 
      text-align:center; 
      font:bold 1.2em Arial;

    }

    /* 
       When writing multiple media queries that don't explicitly
       specify a range, the order of the queries matter!!!

       For example:

	         With a viewport of 400px wide, both of the the following 
	         two queries would apply:

           @media screen and (max-width:400px) {...}
   	       @media screen and (max-width:600px) {...}

	     So, the last one would be used.	
    */

    /*
       Note that this query uses "min-width", 
       not "max-width" so that it handles
       all viewports bigger than 1200       
    */
    @media screen and (min-width: 1201px) {
      body { background-color: orange; }
      p:after { content: "over 1200px"; }
    }

    /* 
       Here, we're using "max-width" to handle
       viewports up to the specified sizes:
    */
    @media screen and (max-width: 1200px) {
      body { background-color: yellow; }
      p:after { content: "961px to 1200px"; }
    }

    @media screen and (max-width: 960px) {
      body { background-color: blue; }
      p:after { content: "769px to 960px"; }
    }

    @media screen and (max-width: 768px) {
      body { background-color: grey; }
      p:after { content: "551px to 768px"; }
    }

    @media screen and (max-width: 550px) {
      body { background-color: green; }
      p:after { content: "321px to 550px"; }
    }

    @media screen and (max-width:320px) {
      body { background-color: red; }
      p:after { content: "up to 320px wide"; }
    }
<p></p>