我已经设置了这个代码,以便点击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>
答案 0 :(得分:2)
您应该使用innerWidth
属性来获得window
大小。
如果您需要jQuery
版本,则必须使用$(window).width()
。
此外,if
语句接受expression
,因此您需要if (windowsize == 1920)
。此外,您不需要为同一元素绑定两个click
事件处理程序。
$('.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;
答案 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)
,它应该有效