用惯了vue和react之后可能会慢慢淡忘掉原生的一些操作dom的几种方式,有的时候确实需要我们通过原生的方式进行操作。
今天就说几个 通过原生j s方式修改样式的方法
最简单的就是 直接
dom.style
如果是 长一点的属性名字的话 是通过 驼峰的写法
比如。“backgroun d-color” => backgroundColor
var bottom = document.querySelector('#bottom');
bottom.style.backgroundColor = '#aaa'
setAttribute的方式
bottom.setAttribute('style', 'background-color: #0f0;')
dom.style.cssText
bottom.style.cssText = 'background-color: #00f;color: #f00;'
重写className的方式 修改样式
bottom.className = 'red'
这种方式怎么说 很有可能会覆盖之前写好的样式。最好的方式还是添加上去比较好
这个时候可以通过 classList的方式追加上去。
dom.classList.add(className); // 添加一个类名
dom.classList.remove(className); // 移除一个类名
bottom.classList.add('red')
关注我。 持续更新 前端知识。