<!DOCTYPEhtml>
<htmllang="CH-ZN">
<head>
<metacharset="utf-8">
<title>按键修改DIV属性</title>
<styletype="text/css">
*{
margin:0;
padding:0;
}
body{
text-align:center;
}
button{
margin-top:20px;
width:100px;
height:60px;
background-color:green;
color:#fff;
border:none;
}
div{
width:400px;
height:400px;
background-color:black;
margin:20pxauto;
display:block;
transition:all1s;
}
</style>
</head>
<body>
<button>变宽</button>
<button>变高</button>
<button>变色</button>
<button>变圆</button>
<button>隐藏</button>
<button>重置</button>
<div></div>
<scripttype="text/javascript">
/**
*修改属性
*@param1元素
*@param2属性(注意这里是字符串类型)
*@param3属性值
*/
letchangeStyle=(ele,attr,value)=>{
//注意:这里的attr为字符串,如果用.attr的方式则无用
ele.style[attr]=value;
}
/**
*随机生成rgb颜色
*@param1最小值
*@param2最大值
*/
letchangeColor=(min,max)=>{
r=Math.floor(Math.random()*(max-min)+min);
g=Math.floor(Math.random()*(max-min)+min);
b=Math.floor(Math.random()*(max-min)+min);
return'rgb('+r+','+g+','+b+')';
}
window.onload=function(){
constbuttons=document.querySelectorAll('button');
constdivBox=document.querySelector('div');
letchangeAttrs=newArray('width','height','background','borderRadius','display','display');
for(leti=0;i<buttons.length;i++){
buttons[i].addEventListener('click',function(){
//当按下重置按钮后将重置样式
i==buttons.length-1&&(divBox.style.cssText='');
//只有当且每次按下变色的时候随机生成颜色
letbgColor=i==2?changeColor(0,255):'';
letchangValues=newArray('600px','600px',bgColor,'50%','none','block');
changeStyle(divBox,changeAttrs[i],changValues[i]);
});
}
}
</script>
</body>
</html>
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h56550.shtml