我的脚本遇到的问题是,它在加载时工作正常,但例如,如果您在移动 View (小于 500px)中开始并单击按钮,它会正确隐藏/显示 div 并阻止链接可点击。但是,如果您将屏幕大小调整为桌面,移动功能仍在运行,并在单击时显示 div 并阻止链接可单击。
如果您在桌面 View 中启动并转到移动设备,则反之亦然,桌面功能仍会在移动 View 中触发
有人知道我做错了什么吗?
https://jsfiddle.net/x2w3vp5n/1/
var fluid = function() {
if ($(window).width() >= 500) {
desktop();
} else {
mobile();
}
};
// Fire on DOM ready
fluid();
// Fire upon resize
$(window).resize(fluid);
function desktop() {
$('.container').on({
mouseenter: function(e) {
$(this).addClass('active');
},
mouseleave: function(e) {
$(this).removeClass('active');
}
});
}
function mobile() {
$('.btn').on('click', function(e) {
var $this = $(this).closest('.container');
e.preventDefault();
e.stopPropagation();
$this.toggleClass('active');
return false;
});
}
最佳答案
您需要“取消注册”页面首次加载时设置的处理程序。
您使用 $().on
附加的任何函数都将继续触发,直到您使用 $().off()
之类的东西取消附加它。
由于您的 mobile
和 desktop
函数绑定(bind)到 DOM 的不同部分,因此您只需删除每个函数顶部的相反函数的事件绑定(bind)即可:
var fluid = function() {
if ($(window).width() >= 500) {
desktop();
} else {
mobile();
}
};
// Fire on DOM ready
fluid();
// Fire upon resize
$(window).resize(fluid);
function desktop() {
//turn off mobile function attached to .btn
$('.btn').off();
$('.container').on({
mouseenter: function(e) {
$(this).addClass('active');
},
mouseleave: function(e) {
$(this).removeClass('active');
}
});
}
function mobile() {
//turn off desktop function attached to .container
$('.container').off();
$('.btn').on('click', function(e) {
var $this = $(this).closest('.container');
e.preventDefault();
e.stopPropagation();
$this.toggleClass('active');
return false;
});
}
关于javascript - 在移动或桌面视口(viewport)中时 jQuery 触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859392/