<html>
<head>
<title></title>
</head>
<style>
#div1{
width:100px;
height:200px;
background:red;
}
</style>
<script>
function setAttr(name,value){
document.getElementById('div1').style.width='200px'
}
window.οnlοad=function(){
document.getElementById('setAttr1').οnclick=function(){
document.getElementById('div1').style.width='200px'
}
}
</script>
<body>
<input type="button" οnclick="setAttr()" value="设置属性" />
<input id="setAttr1" type="button" value="设置属性"/>
<div id="div1"></div>
</body>
</html>
两个按钮实现的效果是一样的,第一个按钮是行间事件,第二个是按钮事件与html分离了。第二个按钮的函数是在window.onload函数里,这是因为window.onload函数是等dom树加载完再执行,如果不加,获取document.getElementById('setAttr1')这个id就会报错,下面的body没有加载,不存在setAttr1这个id