为什么实现不了效果?

来源:2-6 编程练习

JovetWang

2020-03-15 20:01:35

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HTML事件</title>
</head>
<script type="text/javascript">
function BGgreen(ele){
ele.setAttribute("background-color","green");
}
</script>
<body>
    <!-- 此处写代码 -->
   <button onclick="BGgreen(this)">点击我试试</button>
</body>
</html>


写回答

2回答

好帮手慕码

2020-03-16

同学你好,setAttribute() 方法添加指定的属性,并为其赋指定的值。

所以无论是“ele.setAttribute("background","green");”还是“ele.setAttribute("background-color","green");”是给button添加了一个属性并赋值:

http://img.mukewang.com/climg/5e6ed82709bad72604340052.jpg

但是background这个属性,在js中是属于style对象的,所以这样写不会生效。正确写法应该是如下:

http://img.mukewang.com/climg/5e6ed86209f2034604360073.jpg

祝学习愉快~

1

好帮手慕码

2020-03-15

同学你好,这样写是不对的,如下:

http://img.mukewang.com/climg/5e6e20fd09b9763205410034.jpg

红框的意思是添加了一个class为background-color,值给green。背景颜色应该是style中的属性,建议修改:

http://img.mukewang.com/climg/5e6e2127092b086304720060.jpg

祝学习愉快~

0
hovetWang
h 不是很明白 ele.setAttribute("background","green"); 那这样是不是就可以了???
h020-03-15
共1条回复

0 学习 · 40143 问题

查看课程