jQuery onClick:如何根据窗口大小切换不同的类?

时间:2017-02-15 07:47:42

标签: javascript jquery html css

我已经设置了这个代码,以便点击div。切换和删除一个类。现在我想在不同大小的窗口中添加不同的类。 我写了下面的代码,但这段代码不起作用。 这是我的代码:

$('.click').click( function() {
	 var windowsize = $window.width();
	     if (windowsize = 1920) {
    $(".add").toggleClass("new920");
	}
} );
$(".click").click(function(){
		 var windowsize = $window.width();
	     if (windowsize = 1280) {
    $(".add").toggleClass("new280");
	}
});
.click{ border:1px solid #CCC; width:100px; height:20px;}
	.add{ width:200px; height:300px; background:#ccc;}
	.new920{ background:red !important;}
	.new280{ background:green !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<html>
<head>
  
</head>

<body>
    <div class="click">click</div><br/>
    <div class="add">Add</div>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

您应该使用innerWidth属性来获得window大小。

如果您需要jQuery版本,则必须使用$(window).width()

此外,if语句接受expression,因此您需要if (windowsize == 1920)。此外,您不需要为同一元素绑定两个click事件处理程序。

&#13;
&#13;
$('.click').click( function() {
	 var windowsize = window.innerWidth;
	 if (windowsize == 1920) {
            $(".add").toggleClass("new920");
	 }
         if (windowsize == 1280) {
            $(".add").toggleClass("new280");
         }
});
&#13;
.click{ border:1px solid #CCC; width:100px; height:20px;}
	.add{ width:200px; height:300px; background:#ccc;}
	.new920{ background:red !important;}
	.new1280{ background:green !important;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<html>
<head>
  
</head>

<body>
    <div class="click">click</div><br/>
    <div class="add">Add</div>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

You are trying to access the window object with a false syntax. It's $(window) instead of $window ;)

The following should work.

Note: Do you really want to check for a specific width of the window? I assume you rather want to check if the width is smaller than / greater than (windowsize <= 1280). Otherwise it's very unlikely that this condition will be met. Furthermore, you might want to check for innerWidth() of the windows size. It's more accurate and represents the size of the space that can display your content.

$('.click').click( function() {
   var windowsize = $(window).width();
    if (windowsize == 1920) {
      $(".add").toggleClass("new920");
    }
});

$(".click").click(function(){
   var windowsize = $(window).width();
   if (windowsize == 1280) {
    $(".add").toggleClass("new280");
  }
});

答案 2 :(得分:0)

$window更改为$(window),它应该有效