[英]Jquery - Click event on resize() not work properly
I have a problem with jquery's resize() method and click event: in the example below, resizing the window, the click event only works in a some pixels.我对 jquery 的 resize() 方法和单击事件有问题:在下面的示例中,调整窗口大小时,单击事件仅适用于某些像素。 For example, resizing width of window one pixel at a time will work some times yes some times not.
例如,一次调整一个像素的窗口宽度有时会起作用,有时不会。 Why this behavior?
为什么会有这种行为?
if I take the click event out of my code, toggleClass works fine for every pixel.如果我从我的代码中删除点击事件,toggleClass 对每个像素都可以正常工作。
I have tried with both firefox and chrome.我已经尝试过 Firefox 和 chrome。
EDIT: I need the click to work only when the window width is resized below a given size.
编辑:只有当窗口宽度调整到给定大小以下时,我才需要单击才能工作。
jquery:查询:
$(document).ready(function(){
$(window).resize(function() {
if ($(window).width() < 1000) {
$(".button").click(function() {
$("#box").toggleClass("open");
});
}
});
});
css: css:
#box {
width: 300px;
height: 300px;
background-color: red;
}
#box.open {
background-color: green;
}
html: html:
<body>
<div id="box"></div>
<button class="button">Click</button>
</body>
This is because you're adding multiple click events every time the window is resized, so after a few resizes, one single click will toggleClass
, toggleClass
, toggleClass
... times how many pixels window was resized.这是因为您每次调整窗口大小时都会添加多个单击事件,因此在几次调整大小后,单击一次将
toggleClass
、 toggleClass
、 toggleClass
... 乘以调整窗口大小的像素数。
$(window).resize(function() {
// Every time window resize do this:
// Add new click event
$(".button").click(function() {
$("#box").toggleClass("open");
});
});
-- Edit -- - 编辑 -
If it's just for a specific window size, you don't really need the resize
part.如果它只是针对特定的窗口大小,则您实际上并不需要
resize
部分。
You can just check the window size on every click.您可以在每次点击时检查窗口大小。
This should be enough:这应该足够了:
$(document).ready(function() { $(".button").click(function() { if ($(window).width() < 1000) { $("#box").toggleClass("open"); } }); });
#box { width: 300px; height: 300px; background-color: red; } #box.open { background-color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="box"></div> <button class="button">Click</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.