0
点赞
收藏
分享

微信扫一扫

原生JavaScript读写CSS样式的方法

在觉 2021-09-25 阅读 41
前端

好久没用原生 js 读写CSS样式,差点忘了,记录一下!

  1. 通过 DOM 节点对象的style对象
var element = document.getElementById('id');
element.style.color = 'red';
  1. 通过 Element 对象的 setAttribute()、getAttribute()、removeAttribute() 方法
var element = document.getElementById('id');
element.setAttribute('color', 'red')
  1. 通过 style 对象的 cssText 属性、setProperty()、removeProperty() 方法
var element = document.getElementById('id');
element.style.cssText = 'color: red';
element.style.setProperty('color', 'red', 'important');
element.style.removeProperty('color');
element.style.cssText = '';  // 快速清空该规则的所有声明
  1. 直接添加样式表
    1) 创建 <style> 标签,内联样式
var style = document.createElement('style');
style.innerHTML = 'body{color: red}';
document.head.appendChild(style);

2) 添加外部样式表

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', 'reset-min.css');
document.head.appendChild(link);
  1. 还有很多…
举报

相关推荐

0 条评论