我有这个功能,当您单击 html 时,它会检查多个元素的宽度并将其与窗口宽度进行比较。我无法让它与调整大小功能一起使用。我想我叫错了。
$(document).ready(function() {
$(window).resize(function() {
var conditionWidth = checkWidth()
});
function checkWidth() {
var elementWidth = 1;
$("div>div").each(function() {
if ($(this).width() > $("html").width() / 2) {
elementWidth = 2;
}
});
return elementWidth;
}
var conditionWidth = checkWidth()
$("body").off("click").click(function() {
alert(conditionWidth);
});
})
div div {
position: relative;
height: 100px;
width: 100px;
margin-top: 20px;
}
.rectangle1 {
background-color: black;
width: 100px;
}
.rectangle2 {
background-color: red;
width: 200px;
}
.rectangle3 {
background-color: black;
width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<div class="rectangle1"></div>
<div class="rectangle2"></div>
<div class="rectangle3"></div>
</div>
最佳答案
由于您使用 var
在调整大小处理程序中声明变量,因此该变量是调整大小处理程序方法的本地变量,并且闭包范围(dom 就绪处理程序)的值不会更新。
$(document).ready(function () {
var conditionWidth = checkWidth()
$(window).resize(function () {
//when you use var it becomes a local variable
conditionWidth = checkWidth()
});
function checkWidth() {
var elementWidth = 1;
$("div>div").each(function () {
if ($(this).width() > $("html").width() / 2) {
elementWidth = 2;
}
});
return elementWidth;
}
$("body").off("click").click(function () {
alert(conditionWidth);
});
})
关于javascript - 调整大小和调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29369888/