我刚刚发现了另一个可能对您有所帮助的问题。
我正在使用 jQuery,并且我有 window.resize 事件来调用一个函数,该函数将重新定位附加到正文的 div。
现在,当我设置附加 div 的 LEFT css 属性时,window.resize 事件会因没有好的理由而触发。
它会导致无限循环,一次又一次地触发 window.resize。
没有修复的代码:
$(window).resize(function(){
var onResize = function(){
//The method which alter some css properties triggers
//window.resize again and it ends in an infinite loop
someMethod();
}
window.clearTimeout(resizeTimeout);
resizeTimeout = window.setTimeout(onResize, 10);
});
解决方案:
var winWidth = $(window).width(),
winHeight = $(window).height();
$(window).resize(function(){
var onResize = function(){
//The method which alter some css properties triggers
//window.resize again and it ends in an infinite loop
someMethod();
}
//New height and width
var winNewWidth = $(window).width(),
winNewHeight = $(window).height();
// compare the new height and width with old one
if(winWidth!=winNewWidth || winHeight!=winNewHeight){
window.clearTimeout(resizeTimeout);
resizeTimeout = window.setTimeout(onResize, 10);
}
//Update the width and height
winWidth = winNewWidth;
winHeight = winNewHeight;
});
所以基本上它会检查高度或宽度是否改变(只有当你实际调整窗口大小时才会发生这种情况)。