元素设置方式
对以下代码用js设置样式有几种方法
<div id="box">我是一个盒子</div><button id="btn">点击变色</button>
最简单直接的就是
1. 对象.style
var box = document.getElementById('box')var btn = document.getElementById('btn')btn.onclick = function () {box.style.backgroundColor='coral'}
2.对象.className
var box = document.getElementById('box')var btn = document.getElementById('btn')btn.onclick = function () {box.className='sdf'}
在这里将类名变为sdf,在页面上设置了sdf的样式,也要注意改变的话,会覆盖之前设置好的样式
.sdf{background-color: coral;}
3.对象.setAttribute(“style”)
var box = document.getElementById('box')var btn = document.getElementById('btn')btn.onclick = function () {box.setAttribute('style','background-color: coral')}
4.对象.setAttribute(“class”)
var box = document.getElementById('box')var btn = document.getElementById('btn')btn.onclick = function () {box.setAttribute('class','sdf')}
5.对象.style.setProperty(“CSS属性”, “CSS属性值”)
var box = document.getElementById('box')var btn = document.getElementById('btn')btn.onclick = function () {box.style.setProperty('background-color','coral')}
6.对象.style.cssText
var box = document.getElementById('box')var btn = document.getElementById('btn')btn.onclick = function () {box.style.cssText='background-color: coral;'}