首页 > 解决方案 > 如何在 css 文件中使用 API 颜色变量?

问题描述

background-color从 API 中得到一个变量名settings.brand_color。我想在 html 元素中使用该变量。我不能使用style属性,因为我:before在我的应用程序中使用了选择器。我想在我的 css 文件中传递那个 API 变量并在我的:before伪选择器中使用它。

JSX

      <input
        id={languageLabel}
        type="radio"
        name="language-select"
        value={languageLabel}
        // defaultChecked={index === 0}
        onChange={() => {
          onLanguageChange(language, languageLabel);
        }}
        className="focus:ring-0  mr-5 my-18p default-style radio__input"
      />
      <div className="radio__radio"></div>

CSS

.radio__radio {
  width: 24px;
  height: 24px;
  background-color: #d8d8d8;
  border-radius: 50%;
  box-sizing: border-box;
  padding: 6px;
  margin-right: 20px;
  z-index: 1;
}

.radio__radio::after {
  content: "";
  width: 100%;
  height: 100%;
  display: block;
  background: #f28b46;
  border-radius: 50%;
  transform: scale(0);
  z-index: 9;
}

标签: javascripthtmlcssreactjscss-selectors

解决方案


虽然您不能直接在 JS 中设置伪元素的样式,但您可以设置一个 CSS 变量,这可以通过伪元素的类设置来获取。

.radio__radio {
  width: 24px;
  height: 24px;
  background-color: #d8d8d8;
  border-radius: 50%;
  box-sizing: border-box;
  padding: 6px;
  margin-right: 20px;
  z-index: 1;
  --bg: #f28b46; /* ADDED for initial condition */
}

.radio__radio::after {
  content: "";
  width: 100%;
  height: 100%;
  display: block;
  background: var(--bg);
  border-radius: 50%;
  transform: scale(0);
  z-index: 9;
}

然后在您的 Javascript 中,当您获得新的背景颜色时:

document.querySelector('.radio__radio').style.setProperty('--bg', newvalue);

或者当然选择所有此类单选按钮并根据需要更改每个单选按钮。


推荐阅读