JavaScript 获取和修改 CSS 变量

Window.getComputedStyle()

Window.getComputedStyle()方法返回一个对象,该对象包含元素的所有 CSS 属性的值。


获取元素属性

<style>
 #elem-container{
   position: absolute;
   left:     100px;
   top:      200px;
   height:   100px;
 }
</style>

<div id="elem-container">dummy</div>
<div id="output"></div>

<script>
  function getTheStyle(){
    let elem = document.getElementById("elem-container");
    let theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
    document.getElementById("output").innerHTML = theCSSprop;
   }
  getTheStyle();
</script>


获取 CSS 变量

<script>
// 获取根元素
var r = document.querySelector(':root');

// 创建获取变量值的函数
function myFunction_get() {
  // Get the styles (properties and values) for the root
  var rs = getComputedStyle(r);
  // Alert the value of the --blue variable
  alert("The value of --blue is: " + rs.getPropertyValue('--blue'));
}

// 创建设置变量值的函数
function myFunction_set() {
  // Set the value of variable --blue to another value (in this case "lightblue")
  r.style.setProperty('--blue', 'lightblue');
}
</script>


参考:

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle

https://www.w3school.com.cn/css/css3_variables_javascript.asp

https://wow.techbrood.com/fiddle/32675

修改时间 2022-02-19

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
随机推荐
WordPress RESTful API 路由代码结构
WordPress 设置菜单
WordPress 主题激活和取消激活钩子
WordPress 的用户角色和权限
WordPress 用户信息
WordPress 发送邮件
p 标签里面不能嵌套块级元素
WordPress关闭自动草稿