老师 帮忙检查一下代码
来源:3-10 编程练习
慕容5288970
2021-08-14 09:27:34
相关代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<script>
const [p1,p2,p3]=document.querySelectorAll('p')
// 方法1使用对象格式给元素同时设置多个属性
// const m = new Map([
// [
// p1,
// {
// color: 'red',
// backgroundColor: 'yellow',
// fontSize: '40px'
// }
// ],
// [
// p2,
// {
// color: 'green',
// backgroundColor: 'pink',
// fontSize: '40px'
// }
// ],
// [
// p3,
// {
// color: 'blue',
// backgroundColor: 'orange',
// fontSize: '40px'
// }
// ]
// ]);
// m.forEach((propObj, elem) => {
// for (const p in propObj) {
// elem.style[p] = propObj[p];
// }
// });
//方法2:使用forEach
function fun(color,backgroundColor,fontSize){
return new Map([
['color',color],
['backgroundColor',backgroundColor],
['fontSize',fontSize]
]);
}
const m=new Map([
[p1,fun('red','yellow','40px')],
[p2,fun('green','pink','40px')],
[p3,fun('blue','orange','40px')]
]);
// forEach遍历中,第一是参数是键名,第二个参数是键值。可以输出查看下结果,其中第一个参数value表示属性值,styleName 表示属性名,
m.forEach((property,elem)=>{
property.forEach((value,styleName)=>{
console.log(styleName,value)
elem.style[styleName]=value
})
})
</script>
</body>
</html>
1回答
好帮手慕星星
2021-08-14
同学你好,两种方式都没问题,实现效果很棒。继续加油,祝学习愉快!
相似问题