How do I pass parameters to JS through CSS

1. Background that needs to pass parameters through CSS

There are many uses of media queries in CSS, such as device size judgment, whether it supports mouse behavior, whether it is dark mode, whether it is power saving mode, etc.

For example, the dark mode and dark theme that are often mentioned recently:

@media (prefers-color-scheme: dark) { 
    /* dark mode, dark theme*/ 
} 

@media (prefers-color-scheme: light) { 
    /* light theme*/ 
}

CSS can be automatically detected, but sometimes, in JS, we also need to implement different interaction logic or render different content based on different system themes.

How to do? It seems that there is no ready-made JS API to detect the system mode for a while, so I can only use CSS to pass parameters. This is a typical scenario, and there are many similar scenarios.

Updated on 2020-02-26

Media query is detected by JS API, which is window.matchMedia()supported by IE10+ browser.

E.g:

1. CSS and JS border width consistency

When we are doing responsive layout, we often need to set a critical width value. For example, when the width of the device is less than 640 pixels, we consider it to enter the mobile terminal; or when the width is less than 480 pixels, then Use mobile layout, etc.

At this time, the JavaScript code also needs to achieve different interaction effects according to this critical width. When it is larger than that, it is the interaction of the PC, and when it is smaller, it is the interaction under the mobile terminal layout.

Many people agree on CSS code and JS code during actual development, for example:

@media screen and (max-width: 480px) { 
    /* Responsive layout under small screen width*/ 
}
if (screen.width <480) { 
    /* Interactive behavior under small screen width*/ 
}

If there is a problem with this agreement, after a period of time for the project, it is found that there is a problem with this critical width. For example, when the mobile phone is horizontally screened, its width is greater than 480pxthat of the mobile terminal, so the development is Changed to 640px.

@media screen and (max-width: 640px) { 
    /* Responsive layout under small screen width*/ 
}

As a result, if you forget this judgment in the JS code, a bug will appear as a result.

If the screen judgment in our JavaScript code was based on CSS passing parameters when it was originally implemented, then there would be no maintenance problems like this.

2. Does the browser support: hover pseudo-class interaction

We will develop some ui components, hoping to be universal on desktop and mobile terminals, as well as IoT devices.

Some components on the desktop when we use mouseenteror mouseoverevents to achieve the experience is still very good, very convenient. But if these things are used on the mobile terminal and some other touch-screen devices, the world will be problematic, because there is no such thing as hover.

Fortunately, the CSS code is about whether the browser supports the :hover pseudo-type interactive media query judgment (this query has a special article introduction, click here ):

@media (any-hover: none) { 
    /* The device does not support hover events*/ 
}

Unfortunately, there is no such API for direct judgment in JS. Many people should make judgments by judging whether the browser supports touchstartsuch events. Unfortunately, this method of judgment is inaccurate. Because many touch devices can also be connected to mouse devices, the hover event should also be well supported at this time.

Therefore, the final method is to judge by CSS media query, and then pass the judgment result to js in the form of parameters.

Okay, here comes the question. These three cases are mentioned above. How do we pass our parameters to the JS code through CSS?

Second, the method of passing CSS to JS

Usually use CSS to pass parameters to JS, I use the following two methods.

1. Content pseudo-element content passing parameters

E.g:

@media (any-hover: none) {
    body::before {
        content: 'hoverNone';
        display: none;
    }
}

At this point, you can get the information passed by the body pseudo-element through the JS code:

var strContent = getComputedStyle(document.body,'::before').content; 
// The result of strContent is'none', which means that hover is supported 
// The result of strContent is'"hoverNone"' which means that hover is not supported and needs to be replaced click event

This article embeds the above CSS code. Therefore, in the Chrome browser, open the console, enter the mobile preview mode, enter the JS test, you can see that the string information passed by our CSS has been obtained by JS.

The result of running JS on the current article page

At this point, we can ::before::afterpseudo-elements with the contentproperty, learn CSS in the information transfer.

The advantage of this method of passing parameters is that the compatibility is relatively good, but the shortcomings are also obvious. That is, the number of parameter values ​​we pass is limited. If we want to pass multiple values ​​at once, we are a little stretched. You can try the following method, with the help of CSS custom properties.

2. CSS custom properties (CSS variables) pass parameters

Directly on the code, with CSS custom properties (CSS variables) , the development and maintenance of dark mode and light mode becomes relatively easy. In addition, this CSS custom property can also be used for JS Do pattern recognition.

:root {
    --mode: 'unknown';
}
@media (prefers-color-scheme: dark) {
    /* 黑暗模式 */
    :root {
         --mode: 'dark';
         --colorLink: #bfdbff;
         --colorMark: #cc0000;
         --colorText: #ffffff;
         --colorLight: #777777;
    }
}
@media (prefers-color-scheme: light) {
    /* 浅色主题 */
    :root {
         --mode: 'light';
         --colorLink: #34538b;
         --colorMark: #cc0000;
         --colorText: #000000;
         --colorLight: #cccccc;
    }
}

JS detection code:

var mode = getComputedStyle(document.documentElement).getPropertyValue('--mode').trim(); 
// The mode result is'"dark"', which means dark night theme, dark mode, dark style, and eye protection mode. 
// mode result is other means default mode

For example, the result of running on my computer is the following figure:

Passed value

Other values ​​should be displayed on Mac OS X or mobile devices. Welcome to help test and cut a picture and send me, I will update it in the article.

The traditional advantage of using CSS custom attributes is that it is very flexible, and we can define many, many variables. And in fact, we don't have any need to worry about compatibility issues. why? Because all device browsers that support night mode must support CSS custom properties.

Therefore, on the whole, using CSS custom attributes to pass parameters is the best implementation in the dark mode scene. However, if it is a scenario of responsive layout based on the width of the device, it is contentbetter to use CSS  properties to pass parameters.

Three, conclusion

The recent outbreak of the epidemic, do the math, the small fish in the company’s fish tank have not been fed for 3 weeks, and the water level is estimated to be only 50 to 60% now. If you don’t starve to death or freeze to death, alas, it’s a beautiful fish from a colleague, I don’t know. Can I resume work next week? I pray that I can resume work and go to work.

The bats in the remote mountainous areas stirred their wings, and the small fish in our company's fish tank starved to death.

The world is really unpredictable.

Alas, there is nothing else to say.

Welcome to forward and welcome to share.

Guess you like

Origin blog.csdn.net/lu92649264/article/details/112599313