Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JS variable in CSS

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "how to use JS variables in CSS", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use JS variables in CSS" article.

Fantasy

I used to think like this when I was working on a project:

{{color}} export default {data () {return {color: 'red'} H2 {color: this.color;}

Of course, when you think about it, it's impossible. JS and CSS belong to different contexts. Where does CSS get this?

So how can I use the JS variable in CSS? Then you can only manipulate DOM with JS and stuff variables into style, such as getting the DOM element with ref, and then dom.style.color = this.color.

Or in the template:

Vueexport default {data () {return {color: 'red'}

However, this approach is still flawed, for example, it is not recommended to write the style in the style attribute, and variable reuse will be very troublesome, for example, a group of DOM elements all want to use this variable, so you have to give this group a class name, and then document.getElementsByClassName () in mounted. After getting the DOM collection, you have to cycle through each element, adding dom.style.color = this.color for it, wasting a lot of performance.

In fact, CSS itself has many defects, which is not perfect, which leads to the emergence of all kinds of preprocessors: Sass, Less, Stylus, etc.

They provide many features for CSS: loops, conditional statements, variables, functions, etc.

One of the features that is very useful is variables! So CSS also introduced the concept of variables, since there are CSS variables, a lot of things are really much easier, through JS to manipulate CSS variables, and then use CSS variables where needed, this method is much more efficient than before.

What is a CSS variable

In JS (not only JS, but all languages are similar), variables have the following features:

Statement

Use

Scope

Statement

To make it easier to understand, let's use an analogy in JS's way:

Var color = 'red'

In CSS is the same as:

-- color: red

Of course, this is not quite the same as JS, but it should be easy to understand if you learn a language like PHP or Sass. In PHP or Sass, when you declare a variable without a keyword, you add a dollar sign $to the first place of the variable name, which represents the declaration of the variable.

PHP:

$color = 'red'

Sass:

$color: color

But the $sign is occupied by Sass, and the @ sign is occupied by less, so CSS can only think of other symbols. The symbol of CSS is two minus signs--

Use

It doesn't make much sense just to declare a variable, it's valuable only if you use it:

JS:

Console.log (color)

You can see that var is just a keyword that declares a variable, and color is the variable name.

PHP:

Echo $color

Scss:

H2 {color: $color;}

But in PHP or Sass, you have to take it with you when you declare a variable, and you have to take it when you use it.

This confuses many developers, so CSS uses a function called var () when using variables:

CSS:

H2 {color: var (--color);}

Although, like PHP and Sass, you call with a prefix (because that's part of the variable name), the difference is that you need to wrap the variable with a var ().

Scope

This is easy to understand. There is a scope not only in JS, but also in CSS, such as:

JS:

Var color = 'red';function H2 () {console.log (color);} function div () {var color =' blue'; console.log (color);} H2 (); / / reddiv (); / / blue

Similar to the one in CSS:

Body {--color: red;} H2 {color: var (--color); / * * what is obtained here is a globally declared variable with a value of red * * /} div {--color: blue; color: var (--color); / * * a locally declared variable with a value of blue * * /}

That is, the scope of a variable is the valid scope of the selector in which it is located.

Chinese CSS variable

Once I saw two thought-inspired libraries and found that CSS variables could still be played this way:

Chinese-gradient

Chinese-layout

From their names, we can see that they all start with chinese, so there is a high probability that they are CSS variables made in Chinese.

In other words, the CSS variable is very inclusive, unlike in the past when programming must be named in English, the Chinese can also run perfectly this time, do not believe us to try:

Document / * clear the default style * / * {padding: 0; margin: 0} ul {list-style: none} / * full screen display * / html, body, ul {height: 100%} / * write the nine grid on the parent element * / ul {display: grid; grid: var (--nine grid) Gap: 5px} / * Color child elements * / li {background: var (--auroral green)}

That is, the CSS variable can be defined as follows:

Body {--turquoise: aquamarine;}

Then when it is called:

H2 {color: var (--turquoise);} variables in vue

So how can you use the variables declared in * in vue3?

First, let's create a vite project that supports vue3:

Npm init vite-app vars

Then go to the folder to install the dependencies:

Cd vars

Npm i

Then create a component that looks like this:

{{color}} export default {data () {return {color: 'red'}} H2 {color: var (--color);}

Remember what the imaginary components were written at the beginning of the article:

H2 {color: this.color;}

But no matter how awesome vue is, it is impossible to install a this for CSS, unless it makes another preprocessor, but this time using the CSS variable can be very close to our imaginary component:

H2 {color: var (--color);}

First write a vars= "{}" in the tag, and then write the value you declared in data in curly braces.

Let's try again whether this variable is responsive, and whether changing the this.color value in the tag dynamically will cause a change in the view. Let's try it:

Vueexport default {data () {return {opacity: 0}}, mounted () {setInterval (_ = > {this.opacity > = 1 & & (this.opacity = 0) this.opacity + = 0.2}, 300)} H2 {color: rgb (65,184,131); opacity: var (--opacity);}

You can see that we change the value of this.opacity every 300ms, it maps to the CSS variable, this.opacity changes,-- the value of opacity changes, and the view updates as the data is updated, which is a great feature!

Multiple variables are separated by commas:

Vueexport default {data () {return {border: '1px solid black', color:' red'}} H2 {color: var (--color); border: var (--border);} thinking is greatly inspired

Since the two CSS libraries, chinese-gradient and chinese-layout, have verified the feasibility of Chinese variables in CSS, and I remember that the properties of objects can also be written in Chinese, let's try to see if we can use this dark magic to write Chinese in vue:

Vueexport default {data () {return {'transparency': 0}}, mounted () {setInterval (_ = > {this ['transparency'] > = 1 & & (this ['transparency'] = 0) this ['transparency'] + = 0.2}, 300)} H2 {color: rgb (65,184,131); opacity: var (--transparency);} principle

As you can guess, the high probability is that methods like dom.style.setProperty ('--opacity', this.opacity) are used. Press f12 to open the console. Sure enough, it controls the style attribute of the component element:

But we just used only var,scoped in the tag, so what will it be like if they run into each other?

H2 {color: var (--transparency);}

You can see that Vue compiles the CSS variable the same as the string of random characters after data-v-:

So the problem is, if I define a color property in the global style, I want to use this global CSS variable in the component with the scoped attribute, but once I use the CSS variable in scoped, it will be compiled into:-- 62a9ebed-color, but the global definition is not-- 62a9ebed-color but-- color, so there will be a situation where the global attribute can not be found, how to solve this problem? As a matter of fact, it is very simple, just add a global: after--:

H2 {color: var (--global:color);} the above is about "how to use JS variables in CSS". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about it, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report