blo*_*ngs 22 javascript dom onresize
如果我有这个
window.onresize = function() {
alert('resized!!');
};
Run Code Online (Sandbox Code Playgroud)
我的函数在整个调整大小期间被多次触发,但我想捕获调整大小的完成.这是在IE中.
有任何想法吗?那里有各种各样的想法,但到目前为止对我没有用(例如IE的假设window.onresizeend事件.)
Lan*_*nce 30
在这种情况下,我强烈建议去抖.在我发现的JavaScript中,最简单,有效,最可靠的方法是Ben Alman的jQuery插件,Throttle/Debounce(可以使用或不使用jQuery - 我知道......听起来很奇怪).
通过去抖动,执行此操作的代码将如下所示:
$(window).resize($.debounce(1000, function() {
// Handle your resize only once total, after a one second calm.
...
}));
Run Code Online (Sandbox Code Playgroud)
希望可以帮助别人.;)
当我想在调整大小后做某事时,我总是使用它.调用setTimeout并且clearTimeout没有对调整大小的速度产生任何明显的影响,所以这些调用不是多次问题.
var timeOut = null;
var func = function() { /* snip, onresize code here */};
window.onresize = function(){
if(timeOut != null) clearTimeout(timeOut);
timeOut = setTimeout(func, 100);
}
Run Code Online (Sandbox Code Playgroud)
这不是完美的,但它应该为您提供所需的开始.
var initialX = null;
var initialY = null;
var lastResize = null;
var waiting = false;
var first = true;
var id = 0;
function updateResizeTime()
{
if (initialX === event.clientX && initialY === event.clientY)
{
return;
}
initialX = event.clientX;
initialY = event.clientY;
if (first)
{
first = false;
return;
}
lastResize = new Date();
if (!waiting && id == 0)
{
waiting = true;
id = setInterval(checkForResizeEnd, 1000);
}
}
function checkForResizeEnd()
{
if ((new Date()).getTime() - lastResize.getTime() >= 1000)
{
waiting = false;
clearInterval(id);
id = 0;
alert('hey!');
}
}
window.onresize = function()
{
updateResizeTime();
}
Run Code Online (Sandbox Code Playgroud)