js中元素样式设置的六种方法
·
元素的样式设置六种方法
1、对象.style
2、对象.className
3、对象.setAttribute(“style”)
4、对象.setAttribute(“class”)
5、对象.style.setProperty(“CSS属性”, “CSS属性值”)
6、对象.style.cssText
<style>
.pink {
background-color: pink;
}
</style>
<body>
<div id="box">盒子</div>
<button id="change">变色</button>
</body>
在js文件中获取元素
当点击按钮时给div盒子添加背景颜色
var box = document.getElementById("box");
document.getElementById('change').addEventListener('click',function(){
}
设置的六种方法操作
在事件的处理程序中(函数内)书写
//1、对象.style
box.style.backgroundColor = 'pink'
// 2、对象.className
box.className = 'pink'
// 3、对象.setAttribute("style")
box.setAttribute('style','background-color:pink')
// 4、对象.setAttribute("class")
box.setAttribute('class','pink')
//5、对象.style.setProperty("CSS属性", "CSS属性值")
box.style.setProperty('background-color','pink')
// 6、对象.style.cssText
box.style.cssText = 'background-color:pink'
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)