js中body里能用this来代替吗

<!DOCTYPE html>




star


function init(obj){ obj.bgColor= "black";//这行为什么不能改变网页背景颜色。this不是代表body对象吗。 // alert(123); //var obj=document.getElementById("b1"); 这样就可以获得body对象,能更改网页背景颜色。 //obj.bgColor= "black"; }


请教各位大神,为什么我在body里用this,而无法改变body的背景颜色,必须要用要用id来获取body这个对象。我想了一上午也没想通。请朋友帮忙给说下。

你如果在body便签内使用this,这个this代表的是Window对象,而不是body节点。如果需要获得Body节点,使用obj.document.body。可以通过下面的演示代码测试

<!DOCTYPE html>
<html>
<body bgcolor="#E6E6FA" onload="javascript:init(this);">
<script>
function init(obj){
alert(obj);
alert(obj.document.body.bgColor);
obj.document.body.bgColor= "black";//
}
</script>
<h1>Hello world!</h1>
<p><a href="http://www.w3schools.com">Visit W3Schools.com!</a></p>

<p>The bgcolor attribute is not supported in HTML5. Use CSS instead.</p>

</body>
</html>

谢谢额,明白了。太感谢你的回答了。