使用jQuery更改CSS变量 [英] Change CSS variable using jQuery

查看:111
本文介绍了使用jQuery更改CSS变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用jQuery更改CSS中使用的变量? 简单的例子:

Is it possible to change a variable used in CSS using jQuery? Simple example:

html {
  --defaultColor: teal;
}
.box {
  background: var(--defaultColor);
  width: 100px;
  height: 100px;
  margin: 5px;
  float: left;
}
.circle {
  background: #eee;
  border: 2px solid var(--defaultColor);
  width: 100px;
  height: 100px;
  margin: 5px;
  float: left;
  border-radius: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickToChange" type="button" style="width: 100%;">Click to Change</button>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<br/>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>

例如,如何将可变颜色从蓝绿色更改为红色?这是行不通的.

How can I change the variable color from teal to red for example? This one doesn't work.

$("#clickToChange").click(function(){
  $(html).css("--defaultColor", "red");
});

推荐答案

您可以使用普通JavaScript elem.style.setProperty("variableName", "variableProp");

You may change the css variable using plain JavaScript elem.style.setProperty("variableName", "variableProp");

$("html").on('click', function() {
  
  $("body").get(0).style.setProperty("--color", "hotpink");
  
});

body {
  --color: blue;
  background-color: var(--color);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

click me!

这篇关于使用jQuery更改CSS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆