二者的区别从html代码中看是非常明显的,document包括全部,而document.body只包括<body></body>标签中的内容;可二者在页面视图上的区别也很简单,但似乎不太引人注意!以下代码作为演示:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>无标题页</title>
- <style type="text/css">
- .big{width:200px;height:40px; background-color:Aqua;}
- .little{width:100px; height:20px; background-color:Blue;}
- </style>
- </head>
- <body>
- <div class="big" id="big">
- <div class="little" id="little"></div>
- </div>
- <script type="text/javascript">
- //FF,Chrome
- if(window.addEventListener){
- document.addEventListener('click',function(e){alert('document');},false);
- document.body.addEventListener('click',function(e){alert('document.body');e.cancelBubble=true;},true);
- }
- //IE
- else if(window.attachEvent){
- document.attachEvent('onclick', function(e){alert('document');});
- document.body.attachEvent('onclick', function(e){alert('document.body');e=e||window.event;e.cancelBubble=true;});
- }
- </script>
- </body>
- </html>