用jquery检查屏幕宽度

时间:2016-10-29 04:13:52

标签: jquery media-queries

我有一些像这样的代码:

<script>
$(function(){
    $(".flip").flip({
        trigger: 'hover'
    });
});
</script>

我想检查小于480像素的媒体屏幕是否要将trigger更改为“点击”而不是“再次悬停”。

我尝试过这样的代码,但它还没有成功。

<script>
$(function(){
    if($(window).width() < 480){
        $(".flip").flip({
            trigger: 'click'
        });
    }else{
        $(".flip").flip({
            trigger: 'hover'
        });
    }
});
</script>

我该如何检查屏幕宽度?

3 个答案:

答案 0 :(得分:0)

使用$(window).width()函数

答案 1 :(得分:0)

if($(window).innerWidth() <= 480) {
   ...
}

答案 2 :(得分:0)

检查浏览器中的代码。所以你得到了正确的想法。

function showWidth( ele, w ) {
  $( "div" ).text( "The width for the " + ele + " is " + w + "px." );
}
$( "#getp" ).click(function() {
  showWidth( "paragraph", $( "p" ).width() );
});
$( "#getd" ).click(function() {
  showWidth( "document", $( document ).width() );
});
$("#getw").click(function() {
  showWidth( "window", $( window ).width() );
});
 body {
    background: yellow;
  }
  button {
    font-size: 12px;
    margin: 2px;
  }
  p {
    width: 150px;
    border: 1px red solid;
  }
  div {
    color: red;
    font-weight: bold;
  }
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<body>
 
<button id="getp">Get Paragraph Width</button>
<button id="getd">Get Document Width</button>
<button id="getw">Get Window Width</button>
<div>&nbsp;</div>
<p>
  Sample paragraph to test width
</p>
 
<script>
function showWidth( ele, w ) {
  $( "div" ).text( "The width for the " + ele + " is " + w + "px." );
}
$( "#getp" ).click(function() {
  showWidth( "paragraph", $( "p" ).width() );
});
$( "#getd" ).click(function() {
  showWidth( "document", $( document ).width() );
});
$("#getw").click(function() {
  showWidth( "window", $( window ).width() );
});
</script>
 
</body>