简体   繁体   English

为什么我的基于 getComputedStyle 的语句没有运行?

[英]Why is my statement based on getComputedStyle not running?

I have the following code that I'm using to update the css variable called --changeColor我有以下代码用于更新名为 --changeColor 的 css 变量

const r = document.querySelector(':root');
const currentColor = getComputedStyle(r).getPropertyValue('--changeColor');
console.log(currentColor) //logs #2c988b

function newColor() {

    console.log(currentColor) //logs #2c988b
    
    if (currentColor === '#2c988b') {
        r.style.setProperty('--changeColor', '#000000');        
    }
}

The problem is that the code inside the if statement doesn't seem to run as I imagined it would.问题是 if 语句中的代码似乎没有像我想象的那样运行。 If the condition is changed to say 1 < 2 and I call the function in the console then the code inside the statement is executed.如果条件更改为 1 < 2 并且我在控制台中调用 function 则执行语句中的代码。 So my conclusion is that I'm trying something with the if statement that's not possible.所以我的结论是,我正在尝试用 if 语句做一些不可能的事情。

Can someone please tell me what that is and how to make it work?有人可以告诉我那是什么以及如何使它工作吗?

The problem in your code (I think) is that when you get the CSS variable with你的代码中的问题(我认为)是当你得到 CSS 变量时

const currentColor = getComputedStyle(r).getPropertyValue("--changeColor");

the whitespaces around the variables are kept.保留变量周围的空格。 So you should trim() currentColor before comparing it with a string.因此,在将其与字符串进行比较之前,您应该 trim() currentColor。 Try if something like the following works:尝试以下方法是否有效:

https://stackblitz.com/edit/js-acyb8x https://stackblitz.com/edit/js-acyb8x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM