为什么实现不了效果?
来源: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回答
同学你好,setAttribute() 方法添加指定的属性,并为其赋指定的值。
所以无论是“ele.setAttribute("background","green");”还是“ele.setAttribute("background-color","green");”是给button添加了一个属性并赋值:
但是background这个属性,在js中是属于style对象的,所以这样写不会生效。正确写法应该是如下:
祝学习愉快~
好帮手慕码
2020-03-15
同学你好,这样写是不对的,如下:
红框的意思是添加了一个class为background-color,值给green。背景颜色应该是style中的属性,建议修改:
祝学习愉快~
相似问题