Javascript 访问窗口宽度时未触发onresize事件
我已经将onresize侦听器附加到body标记上,但是当我更改代码以访问Javascript 访问窗口宽度时未触发onresize事件,javascript,onresize,Javascript,Onresize,我已经将onresize侦听器附加到body标记上,但是当我更改代码以访问窗口时,innerWidth和窗口。innerHeight我的调整大小事件只工作一次 <script type="text/javascript"> function showMsg() { document.write((window.innerWidth / window.innerHeight) * 100 + "%"); } </script> <
窗口时,innerWidth
和窗口。innerHeight
我的调整大小事件只工作一次
<script type="text/javascript">
function showMsg()
{
document.write((window.innerWidth / window.innerHeight) * 100 + "%");
}
</script>
<body onresize="showMsg()">
函数showMsg()
{
文件.写入((window.innerWidth/window.innerHeight)*100+“%”;
}
有道理,在函数返回后,您是否尝试检查页面的源代码?这里没有更多的body标签了——你的事件监听器也随之而去(或者仍然在内存中,毫无用处地晃来晃去)尝试将其附加到
窗口
window.onresize = function()
{
document.write((this.innerWidth/this.innerHeight)*100+'%');
};
现在,在以前非常流行的浏览器的旧版本中,这(将事件侦听器附加到窗口对象)会导致内存泄漏。窗口对象从未真正被破坏
如何解决mem问题
(function(win)
{
win.onresize = function()
{
document.write((this.innerWidth/this.innerHeight)*100+'%');
};
if (win.attachEvent)
{
win.attachEvent('onbeforeunload',(function(self)
{
return function freeMem()
{
self.onresize = null;
self.detachEvent('onbeforeunload',freeMem);
};
})(win));
return;
}
win.addEventListener('beforeunload',(functio(self)
{
return function freeMem()
{
self.onresize = null;
self.removeEventListener('beforeUnload',freeMem,false);
};
})(win),false);
})(this);//this points to current window
我知道,看起来很糟糕,但我已经测试过了,它确实起到了作用-谢谢你,也就是说,严格地说,传递给win
到self
的闭包可以省略,但我会将它保存在那里,以确保在onbeforeuload
事件触发时,它绝对可靠,处理程序返回所有超出范围的函数和引用,因此GC没有理由不释放内存在大多数情况下,这都有些过分,但为了以防万一,我决定把它贴在这里…:-P