CSS root variables, also known as CSS custom properties, are a powerful tool for defining reusable values in CSS. One of the biggest benefits of using CSS root variables is that they can be updated dynamically using JavaScript. In this tutorial, we'll show you how to update CSS root variables with just a few simple steps.
【CSS根变量,也称为CSS自定义属性,是一个好用的工具定义CSS中的变量。使用CSS根变量的最大好处之一是可以使用JavaScript动态更新它们。在本示例中,我们将向你展示如何通过几个简单的步骤更新CSS根变量。】
First, we define the CSS root variables under the special :root element.
【首先,我们在特殊的“:root”元素下定义CSS根变量。】
:root {
--primary-color: rgb(99 102 241);
}
Then, we can access the root element using either document.documentElement or querySelector(). Once we have obtained the root element, we can retrieve the computed styles and access any CSS variables.
【然后,我们可以使用document.docentElement或querySelector()访问根元素。一旦我们获得了根元素,我们就可以检索计算出的样式并访问任何CSS变量。】
Here's an example of how to access the primary color variable:
【以下是如何访问基本色变量的示例:】
const root = document.documentElement;
// Or
// const root = document.querySelector(':root');
const primaryColor = getComputedStyle(root).getPropertyValue('--primary-color');
Once we have accessed the CSS root variables, updating them with JavaScript is a piece of cake. We can use the root element to set a new value. For example, to update the primary color variable to blue, we can use the following code:
【一旦我们访问了CSS根变量,用JavaScript更新它们就是小菜一碟。我们可以使用根元素来设置一个新的值。例如,要将原色变量更新为蓝色,我们可以使用以下代码:】
root.style.setProperty('--primary-color', 'blue');
By using CSS root variables and JavaScript together, we can create dynamic and flexible styles for our website or application.
【通过将CSS根变量和JavaScript结合使用,我们可以为我们的网站或应用程序创建动态和灵活的样式。】
资料:
known as
被称为;以…而闻名;被认为是
obtained
v.
(尤指经努力)获得,赢得;存在;流行;沿袭
obtain的过去分词和过去式
retrieve
vt.
检索;取回;检索数据;找回;挽回;索回;扭转颓势
n.
恢复
primary color
原色;基本色
原文:phuoc.ng/collection/… 语雀翻译原文:www.yuque.com/fengjutian/… 《🌟Dynamically update CSS root variables【动态更新CSS根变量】》