原生js练习,前辈的js原生练习,开始跟着做,收货很多。
题目:控制div属性
![](https://img.haomeiwen.com/i4170047/f8cd51de5698d0b4.png)
解题思路:
- 每个按钮进行事件监听。
- 设置css属性(dom.style.css="")
代码:
var btn=document.getElementsByTagName("button");
var div1=document.getElementById("div1");
btn[0].onclick=function () {
div1.style.width="250px";
}
btn[1].onclick=function () {
div1.style.height="250px";
}
btn[2].onclick=function () {
div1.style.background="#36ff40";
}
btn[3].onclick=function () {
div1.style.display="none";
}
btn[4].onclick=function () {
div1.setAttribute("style", "width: 200px;height: 200px;background: #000;")
}
优化:
- 传入的属性,属性值可以组成数组,这样分别传入数组值和属性值对函数进行抽象,这里如果写成对象形式也是可以的(更清晰)。
- 重置按钮,清除style属性的值(dom.style.cssText='')
- 注意for循环形成闭包,这里i一直为5,所以需要把i进行存储
var btn=document.getElementsByTagName("button");
var div1=document.getElementById("div1");
//抽象出改变css的函数
var changeStyel=function (elem,attr,value) {
elem.style[attr]=value;
};
//css属性数组
var nStyle=["width","height","background","display"];
//css属性对应值
var nVal=["250px","250px","#c0ff55","none"];
//遍历
for(var i=0;i<btn.length;i++){
console.log(i);
//闭包,为了获得i的值
btn[i].index=i;
btn[i].onclick=function () {
//判断是否为最后一个重置按钮
if(this.index==btn.length-1){
//重置为空
div1.style.cssText="";
}else{
changeStyel(div1,nStyle[this.index],nVal[this.index]);
}
}
}
网友评论