面向对象的好处是效率高,坏处不利于维护。
需求:需要给3个div,3个p设置边框
样式:
<style>
div {
height: 80px;
margin-top: 20px;
background-color: rgb(47, 102, 255);
font-size: 28px;
text-align: center;
color: rgb(255, 255, 255);
line-height: 80px;
font-weight: 700;
}
p {
height: 80px;
margin-top: 20px;
background-color: rgb(105, 208, 255);
font-size: 32px;
text-align: center;
color: rgb(255, 255, 255);
line-height: 80px;
font-weight: 700;
}
</style>
结构:
<div>前端营地</div>
<div>前端营地</div>
<div>前端营地</div>
<p>Front end camp</p>
<p>Front end camp</p>
<p>Front end camp</p>
行为:
方法1.面向过程的做法
弊端:(1)获取元素代码过长 (2)两个for循环,代码冗余 (3)不便于维护
let divList = document.getElementsByTagName('div')
let pList = document.getElementsByTagName('p')
for (let i = 0; i < divList.length; i++) {
divList[i].style.border = '10px solid black'
}
for (let i = 0; i < pList.length; i++) {
pList[i].style.border = '10px solid black'
}
方法2.使用函数封装
好处:代码复用 弊端:函数名是全局变量,会造成全局变量污染
let divList = tagName('div');
let pList = tagName('p');
setStyle(divList, '10px solid black');
setStyle(pList, '10px solid black');
function tagName(name) {
return document.getElementsByTagName(name);
}
function setStyle(eles, value) {
for (let i = 0; i < eles.length; i++) {
eles[i].style.border = value;
}
}
方法3.使用对象封装
好处:(1)便于维护,以后添加修改方法很方便 (2)避免全局变量污染
let obj = {
tagName: function (name) {
return document.getElementsByTagName(name)
},
setStyle: function (eles, value) {
for (let i = 0; i < eles.length; i++) {
eles[i].style.border = value;
};
}
}
let divList = obj.tagName('div');
let pList = obj.tagName('p');
obj.setStyle(divList, '10px solid black');
obj.setStyle(pList, '10px solid black');
效果展示