javascript - 如何在 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;
}
解决方案
虽然您不能直接在 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);
或者当然选择所有此类单选按钮并根据需要更改每个单选按钮。
推荐阅读
- python-3.x - 遍历元组列表
- ruby-on-rails - ActiveRecord 验证字符串,但能够将部分字符串视为整数
- python - 打开我的网络服务器时,浏览器显示 ERR_INVALID_HTTP_RESPONSE
- raspberry-pi - Raspberry pi - 将权限更改为 700
- javascript - framework7 react - 以编程方式切换选项卡
- python - node.js 发送 POST 请求以进行身份验证
- c# - 如何在 WPF 中将项目添加到 ListView
- c# - WPF 可观察集合
UI 框架元素嵌套 2 类深度 - javascript - 成员函数不能访问其成员属性?
- python - AttributeError:“PosixPath”对象没有属性“写”