一旦窗口大小调整到高于或低于 771 像素,我将使用下面的代码执行我的 jQuery 命令。我如何告诉浏览器仅在超过 771px 时执行一次代码,然后在返回到低于 771px 时再次执行。
jQuery(window).resize(function(){
if (jQuery(window).width() >= 771){
console.log(">");
}
if (jQuery(window).width() < 771){
console.log("<");
}
});
有了这段代码,浏览器窗口每改变一个像素,控制台就会记录一次“<”,所以很多时候,我只希望它在上面时只记录一次,在它回到下方时只需要一次。
最佳答案
浏览器不会为您做这些。您必须保留调整大小事件处理程序,并将先前的宽度保留在变量中。然后将当前的与之前的进行比较。
像这样:
var previousWidth = jQuery(window).width();
jQuery(window).resize(function(){
var currentWidth = jQuery(window).width();
var threshold = 771;
if (previousWidth < threshold && currentWidth >= threshold)
console.log(">");
if (previousWidth >= threshold && currentWidth < threshold)
console.log("<");
previousWidth = currentWidth;
});
关于javascript - jQuery(window).resize 函数只触发一次而不是每个像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24397799/