我有一个问题,我需要在浏览器宽度小于769px时运行一个函数。
我使用 $(window).resize();
来检测浏览器何时变宽。
当我将浏览器的大小调整为例如750px时,该函数会生成一个新的事件堆栈,我的意思是,如果现在我单击按钮,每个事件都会运行两次,如果我更改浏览器宽度再说一遍,700px,现在每个都执行3次。对于浏览器宽度的每次变化,只要小于 769px,就会“堆叠”一个新的事件监听器。
如何在调整浏览器大小时只更新事件而不允许创建新事件?
要重现问题,请按照下列步骤操作:
这是一个link到重现我的问题的 JSFiddle。
- 加载页面
- 点击按钮查看初始行为
- 更改最小浏览器的尺寸769px
- 再次单击按钮查看新行为。
- 将浏览器的宽度调整为较小的 769 像素
- 点击按钮并查看行为,该事件现在运行三次
代码:
var App = function() {
var tempo, body;
var Init = function() {
body = $('body');
$(window).resize(function() {
clearTimeout(tempo);
tempo = setTimeout(showonlyone, 500);
});
showonlyone();
};
var showonlyone = function() {
console.log('Executing now !!!');
var mobileClass = "small-device";
var desktopClass = 'desktop-device';
var windowWidth = getWindowWidth();
if (windowWidth < 769) {
body.addClass(mobileClass);
body.removeClass(desktopClass);
$('a[data-navtrigger]')
.click(
function(e) {
e.stopPropagation();
var triggerTag = $(this);
var triggerName = $(this).attr(
"data-navtrigger");
var activo = true;
var activeClase = 'activoo';
console.log('triggerName: ' + triggerName);
$('a[data-navtrigger]')
.each(
function(index) {
if ($(this).attr(
"data-navtrigger") == triggerName) {
if (!$(this).hasClass(
activeClase)) {
$(this)
.addClass(
activeClase);
} else {
activo = false;
$(this)
.removeClass(
activeClase);
}
} else {
$(this).removeClass(
activeClase);
}
});
$('[data-navtarget]')
.each(
function(index) {
console
.log('triggerName Dentro: ' + triggerName);
if ($(this).attr(
"data-navtarget") == triggerName && activo) {
$(this).slideDown(250);
} else {
$(this).slideUp(250);
}
});
});
} else if (windowWidth > 768) {
body.removeClass(mobileClass);
body.addClass(desktopClass);
$('a[data-navtrigger]').unbind('click');
}
};
var getWindowWidth = function() {
return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
};
return {
init: function() {
Init();
}
};
}();
$(document).ready(App.init);
最佳答案
如果您使用 CSS 媒体查询控制这些类会怎样?然后您可以为指定的类添加行为。
https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
关于javascript - 如何防止函数在调整大小时创建新的事件窗口堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31121485/