<!doctype html> <html lang="es"> <head> <meta charset="utf-8"> <title>HTML5</title> <link rel="stylesheet" href="styles.css" /> <style type="text/css"> #outer{ text-align:center; } #div1 { 200px; height:200px; background:black; display:block; margin:10px auto; } </style> <script type="text/javascript"> var changeStyle = function (ele,att,val){ ele.style[att]=val; } window.onload = function(){//文档加载时给button赋值 try{ var btn = document.getElementsByTagName("button"); var div1 = document.getElementById("div1"); var att = ["width","height","background","display","display"]; var val = ["300px","300px","red","none","block"]; for(var i=0;i<btn.length;i++){ btn[i].index = i;//给每个button赋值,相当于每个button的id btn[i].onclick = function(){ this.index==btn.length-1&&(div1.style.cssText=""); //this相当于被onclick时的button,有一个变量index, //a==b&&c=d ->if(a==b)c=d; //style.cssText它是一组样式属性及其值的文本表示,等于空之后相当于去掉style样式 changeStyle(div1,att[this.index],val[this.index]); } } } catch(err){ alter(err.message); } } </script> </head> <body> <div id="outer"> <button >变宽</button> <button >变高</button> <button >变色</button> <button >隐藏</button> <button >重置</button> </div> <div id="div1" > </div> </body> </html>