如何使用JS编辑CSS变量? [英] How do I edit a CSS variable using JS?

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

问题描述

我有这些CSS变量来控制我的项目的颜色,所以我可以做主题。

I have these CSS variables to control the colors of my project so I can do theming.

html {
    --main-background-image: url(../images/starsBackground.jpg);
    --main-text-color: #4CAF50;
    --main-background-color: rgba(0,0,0,.25);
    --beta-background-color: rgba(0,0,0,.85);
}

但无论我如何尝试更改属性(尝试了两条注释行)另外),我得到的最接近的不是有效属性。

However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.

function loadTheme() {
    var htmlTag = document.getElementsByTagName("html");
    var yourSelect = document.getElementById( "themeSelect" );
    var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
    // htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
    // $("html").css("--main-text-color","#FFCF40");
}

推荐答案

使用<$ c可以更改CSS变量$ c> el.style.cssText 属性,或 el.style.setProperty el.setAttribute 方法。在您的代码段中, el.setAttribute 被错误地使用,这导致您遇到的错误。这是正确的方法:

Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:

var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";

var html = document.getElementsByTagName('html')[0];
html.style.setProperty("--main-background-color", "green");

var html = document.getElementsByTagName('html')[0];
html.setAttribute("style", "--main-background-color: green");

演示

以下演示使用CSS变量定义背景颜色,然后在加载后2秒使用JS片段更改它。

The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.

window.onload = function() {
  setTimeout(function() {
    var html = document.getElementsByTagName('html')[0];
    html.style.cssText = "--main-background-color: red";
  }, 2000);
};

html {
    --main-background-image: url(../images/starsBackground.jpg);
    --main-text-color: #4CAF50;
    --main-background-color: rgba(0,0,0,.25);
    --beta-background-color: rgba(0,0,0,.85);
}

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

这只适用于支持CSS变量的浏览器。

This will only work in browsers supporting CSS variables obviously.

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

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