我错过了什么?HTML>正文 - 调整大小事件

obe*_*iro 8 html javascript

通常添加resize事件的方式(监听窗口大小已更改)是这样的:

//works just fine
window.addEventListener("resize", function(){console.log('w')}, true)
Run Code Online (Sandbox Code Playgroud)

但我想添加这个事件处理程序,document.body甚至更好document(不要问我为什么,但我不能使用窗口)

//this dosn't work
document.body.addEventListener("resize", function(){console.log('b')}, true)

//this also dosn't work
document.addEventListener("resize", function(){console.log('d')}, true)
Run Code Online (Sandbox Code Playgroud)

问题是,这不起作用.我真的不明白为什么?MB我错过了什么?

这工作(但我想再次使用addEventListener)

document.body.onresize = function(){console.log('a')}
Run Code Online (Sandbox Code Playgroud)

那为什么document.addEventListener("resize", function(){console.log('d')}, true)不起作用?


UPD#1

有没有办法捕获window.onresize其他窗口的东西?

UPD#2

如果window是唯一可以调整大小的对象那么为什么这样做?O_O

document.body.onresize = function(){console.log('a')}
Run Code Online (Sandbox Code Playgroud)

sak*_*zai 9

Mozilla Docs说:

"任何元素都可以赋予onresize属性,但只有window对象有resize事件.调整其他元素的大小(比如通过使用脚本修改img元素的宽度或高度)不会引发resize事件."

请查看一个工作示例

function winResize(e){
 console.log('window reiszed',e);

  //body resize when width increases
 document.getElementById('content').innerHTML+='<div style="width:900px;background:green;border:1px solid red">'+Date()+'</div><br/>';
}

function docResize(e){
 cosole.log('document resized');   
}

function bodyResize(e){
 console.log('body resized');
}

window.addEventListener("resize", winResize);
document.body.onresize=bodyResize;
Run Code Online (Sandbox Code Playgroud)

编辑: 如果停止事件,则不会调用bubble.body.onresize事件:例如

 function winResize(e){
     console.log('window reiszed',e);
     e.stopImmediatePropagation()
   }
Run Code Online (Sandbox Code Playgroud)

*更新:*

a)首先要理解的是resize事件将从中传播 window > document > body ,如果你在所有上述节点和其他节点上定义了resize事件,那么事件将向下传播并且每个节点都将被调用

b)当您询问差异b/w window.resize并且[body/document].onresizewindow.resize事件是html4规范中定义的标准事件和[body/document]时.onresize可用作非标准事件(某些浏览器已实现但不是全部)但后一个onresize事件添加在HTML5规范中 身体.

只是为了满足自己去w3c验证网站并使用Doctype验证以下html html 4.01 strict,你会看到它会在onresize属性上抱怨:

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
   <html><head><title>test</title></head> 
   <body onresize="somefunc()">
    <div> On resize validation </div>
    </body>
   </html>
Run Code Online (Sandbox Code Playgroud)

c)结论. window.addEventListener()附带了Dom level 2事件规范,只为该规范中指定的事件添加事件listern(Dom level 3事件也支持这个),读取DOM级别.