[英]jQuery toggleClass doesn't fire work resizing browser?
I have an issue with some code. 我有一些代码问题。 Basically on click of a div the class 'active-sort' should be added/removed (This class changes the position of .sort-by from the top).
基本上,单击div时,应添加/删除“ active-sort”类(此类从顶部更改.sort-by的位置)。 On page load it works great but for some reason the toggleClass doesn't always work when the browser is resized (sometimes it does, sometimes it doesn't).
在页面加载时,它的效果很好,但由于某些原因,在调整浏览器大小时,toggleClass并不总是起作用(有时可以,有时不能)。
I'm not great with this, so was hoping a new set of eyes might be able to instantly see what I'm doing wrong. 我对此并不满意,因此希望能有新的眼光能够立即看到我在做什么错。 Any help would be appreciated.
任何帮助,将不胜感激。
function toggleSortBy() {
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by');
if ($(window).width() > 1024) {
toggle.click(function(){
sortBy.toggleClass('active-sort');
});
} else {
// other code here for smaller devices
}
};
$(window).on('load resize', function() {
toggleSortBy();
});
it's possible you may not need the resize event since you're checking the window size already in the click handler 由于您正在检查点击处理程序中已经存在的窗口大小,因此可能不需要调整大小事件
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by');
toggle.click(function(){
if ($(window).width() > 1024) {
sortBy.toggleClass('active-sort');
} else {
// other code here for smaller devices
}
});
but if you do you should debounce the resize event //css-tricks.com/snippets/jquery/done-resizing-event 但是,如果您这样做,则应该消除调整大小事件// //css-tricks.com/snippets/jquery/done-resizing-event
then you could do something like: 那么您可以执行以下操作:
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by'),
isMobile = false;
toggle.click(function(){
if (isMobile) {
sortBy.toggleClass('active-sort');
} else {
// other code here for smaller devices
}
});
$(window).on('load resize', function() {
// don't forget to debounce you'll see why later on in your development.
isMobile = ($(window).width() > 1024) ? false : true;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.