我正在制作一个响应式网站,到目前为止它运行良好,但我目前遇到的一个问题是,如果我反复快速更改窗口大小,它似乎会忽略 jQuery。当发生这种情况时,应该“显示:无;”的元素当条件满足时留在页面上。
CSS 很简单:
body:after{display:none; content:"default";}
@media only all and (max-width: 800px){
body:after{content:"tablet";}
}
jquery 看起来像这样:
jQuery(document).ready(function($) {
var currentSize = "default";
var lazyLayout = _.debounce(function(e) {
}, 300, true);
$(window).resize(lazyLayout,function() {
var size = window.getComputedStyle(document.body, ':after').getPropertyValue('content');
/* Ridiculous thing to deal with inconsistent returning of
value from query. Some browsers have quotes some don't */
size = size.replace(/"/g, "");
size = size.replace(/'/g, "");
if (size != currentSize) {
if (size == 'tablet') {
var count = $('#mobileNav').length;
if (count < 1) {
var data = {
dataType: "HTML",
action: 'nav_media_query',
nonce: myAjax.nonce
};
$.post( myAjax.url, data, function( data ) {
$('#content-wrapper').removeClass('col-4-5');
$('#trending-Container').addClass('mobileNavStyle');
$('#trending-Container').append(data);
});
currentSize = 'tablet';
}
}
if(size == 'default') {
$('#mobileNav').remove();
currentSize = 'default';
}
}
}).resize();
});//end function
这会检查是否已加载媒体查询但会查找内容属性,然后它会触发 ajax 请求并将一些 wordpress php 加载到元素中。
如果我慢慢调整窗口大小,效果很好,但如果我快速反复调整窗口,它就会崩溃。
是否有一些 jQuery 函数可以用来阻止它崩溃?
编辑:我更新了我的代码以添加 _.js 去抖动方法,这应该有助于限制 ajax 请求。但是仍然存在不再满足要求后元素未被移除的问题。
最佳答案
尝试在等待的调整大小函数中调用一个函数。我不太确定它是否会起作用,但尝试以这种方式在 jquery 中使用延迟函数:
setTimeout(showpanel, 1000)
function showpanel() {
//Code that you want to execute
}
关于javascript - 如果重复触发,元素将忽略 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19392825/