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 CSS variable to achieve heartbeat effect

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

Share

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

This article introduces the relevant knowledge of "how to use CSS variables to achieve heartbeat effect". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Preface

"CSS variable" is also called "CSS custom property". Why do you suddenly mention this thing that few people use? Because recently in the reconstruction of the personal official website, I do not know why suddenly like to use the "CSS variable", perhaps its own hidden charm, so that the author is impressed by it.

When it comes to why variables are used in CSS, here is an example of chestnut, which you will understand at a glance.

/ * do not use CSS variable * / .title {background-color: red;} .desc {background-color: red;} / * use CSS variable * /: root {--bg-color: red;} .title {background-color: var (--bg-color);} .desc {background-color: var (--bg-color);}

After reading it, you may feel that the amount of code using "CSS variable" is a little too much, but have you ever thought that one day the evil planner little brother and designer little sister said they wanted to do a skin-changing function. According to the usual way of thinking, it is estimated that some students will add a new color theme CSS file according to the default color theme. How troublesome it is to maintain several sets of theme colors at the same time for each new demand.

At this point, the "CSS variable" comes in handy, standardizing the colors that need to be changed with the design sister in advance and defining them through the "CSS variable", and operating these defined "CSS variables" in batches through JS. This is also one of the solutions to "changing theme colors". The advantage is that you only need to write a set of CSS code.

["red", "blue", "green"] .forEach (v = > {const btn = document.getElementById (`$ {v}-theme- btn`); btn.addEventListener ("click", () = > document.body.style.setProperty ("- bg-color", v);})

Here is a summary of the benefits of using variables in CSS:

Reduce the repeatability of style codes

Increase the extensibility of style code

Improve the flexibility of style codes

Add a communication mode between CSS and JS

You don't have to traverse DOM deeply to change a style.

Some students may ask that Sass and Less have already implemented the feature of variables, so why bother. But if you think about it, the "CSS variable" has its advantages compared to the variables of Sass and Less.

Native browser features that can be run directly without any translation

A member of the DOM object, which greatly facilitates the connection between CSS and JS

Recognition

I originally planned to spend half the space on the specification and usage of "CSS variable", but a lot of searches on the Internet felt unnecessary. I posted the tutorial "CSS variable course" written by teacher Ruan Yifeng. At the same time, the author also collates the details of the "CSS variable" to facilitate everyone's memory.

Declare:-- variable name

Read: var (--variable name, default)

Types

Normal: can only be used as an attribute value, not as an attribute name

Characters: concatenate "Hello," var (--name) with string

Value: use calc () with var (--width) * 10px in unit of value

Scope

Scope: valid under the current element block scope and its child element block scope

Priority: inline style > ID selector > class selector = attribute selector = pseudo class selector > tag selector = pseudo element selector

Next, use several special scenarios to demonstrate the charm of the "CSS variable". The same sentence, "a thing has a use of the scene, it will naturally have its value", then more and more people will use it.

Working with scen

In fact, the "CSS variable" has a particularly useful scenario, which is used in conjunction with the collection of List elements. If you don't understand what this is, please read on.

All of the following demo code is based on Vue file, but HTML, CSS and JS are written separately. In order to simplify the writing of CSS, Sass is used for preprocessing to facilitate code demonstration.

Strip loading strip

A strip loading bar is usually composed of several lines, and each line corresponds to the same animation with different time delay, and runs the same animation through the time difference, thus producing the loading effect. It is estimated that most of the students will probably write the CSS code like this.

.loading {width: 200px; height: 200px; li {border-radius: 3px; width: 6px; height: 30px; background-color: # f66; animation: beat 1s ease-in-out infinite; & + li {margin-left: 5px } &: nth-child (2) {animation-delay: 200ms;} &: nth-child (3) {animation-delay: 400ms;} &: nth-child (4) {animation-delay: 600ms } &: nth-child (5) {animation-delay: 800ms;} &: nth-child (6) {animation-delay: 1s;}

The analysis code found that each only exists animation-delay is different, while the rest of the code is exactly the same, replaced by other similar List element collection scenario, then there are 10 to write 10: nth-child.

Obviously, this approach is inflexible and not easy to encapsulate into components, and it would be even better if it could be encapsulated into a function like JS and output different styling effects according to the parameters. At this point, it is obvious that it is to pave the way for the development skills of "CSS variables".

For the modification of the HTML section, let each have a "CSS variable" under its own scope. For the modification of the CSS part, you need to analyze which attributes change regularly with the increase of index, and use the expression "CSS variable" instead of the regular change.

.strip-loading {width: 200px; height: 200px; li {--time: calc ((var (--line-index)-1) * 200ms); border-radius: 3px; width: 6px; height: 30px; background-color: # f66; animation: beat 1.5s ease-in-out var (--time) infinite & + li {margin-left: 5px;} Source code link can be obtained at the end of the article.

The variables in the code-- line-index and-- time make each have its own scope. For example, the second value,-- line-index, is 2, and the calculated value is 200ms. When replaced with the third, the two values will be different again.

This is due to the scope of the "CSS variable" (valid under the current element block scope and its child element block scope), so calling-line-index in the. strip-loading block scope is invalid.

/ * invalid flex attribute * / .loading {display: flex; align-items: center; flex: var (--line-index);}

Through the clever use of the "CSS variable", the CSS code is also reduced from 29 lines to 15 lines, and the effect is more pronounced for scenarios with more collections of List elements. And it is more beautiful and easier to maintain. One day, it is said that the time difference in the loading effect is not obvious, so you can directly adjust the 200ms in calc ((var (--line-index)-1) * 200ms) to 400ms. There is no need to modify each: nth-child (n).

Heart-shaped loading strip

Some time ago, when brushing Nuggets saw the heart-shaped loading strip of brother Chen Dayutou, I thought it was very beautiful and full of feeling.

Through the dynamic graph analysis, it is found that the background color of each line is not consistent with the animation delay, and the height of the animation is also different. If you are careful, you may also find that articles 1 and 9 are highly consistent, articles 2 and 8 are highly consistent, and so on, a similar formula for height transformation is obtained: symmetrical index = total + 1-index.

The background color uses the hue rotation hue-rotate function of the filter to make the color transition more natural; the animation delay setting is consistent with the setting of the bar loading bar above. Let's use the "CSS variable" to implement it according to the dynamic graph you see.

.heart-loading {width: 200px; height: 200px; ul {display: flex; justify-content: space-between; width: 150px; height: 10px;} li {--theta: calc (var (--line-index) / var (--line-count) * .5turn) -- time: calc ((var (--line-index)-1) * 40ms); border-radius: 5px; width: 10px; height: 10px; background-color: # 3c9; filter: hue-rotate (--Theta); animation-duration: 1s; animation-delay: var (--time); animation-iteration-count: infinite } .line-1, .line-9 {animation-name: line-move-1;} .line-2, .line-8 {animation-name: line-move-2;} .line-3, .line-7 {animation-name: line-move-3 } .line-4, .line-6 {animation-name: line-move-4;} .line-5 {animation-name: line-move-5;}} source code links are available at the end of the article

After a wave of operation, it has the following effect. Compared with brother Chen Dayutou's heart-shaped loading bar, the color, fluctuation curve and beating frequency are a little different, which is a heartbeat feeling under the spread of warm colors and the surge of adrenaline. I think of a poem I once wrote: I see pity, love it, appreciate both elegance and popularity, and make a good mate of a good man.

Label navigation bar

The above demonstrates the use of "CSS variable" in CSS and some magic tricks through two load bars, and now demonstrates the use of "CSS variable" in JS through the label navigation bar.

There are three main API in JS that manipulate the "CSS variable", which look easy to remember, as follows:

Read variable: elem.style.getPropertyValue ()

Set variable: elem.style.setProperty ()

Delete variable: elem.style.removeProperty ()

First on the effect picture, the main effect is to use the "CSS variable" to mark the background color of each Tab and toggle the display state of the Tab.

Title {{I + 1}} content {{I + 1}}. Tab-navbar {display: flex; overflow: hidden; flex-direction: column-reverse; border-radius: 10px; width: 300px; height: 400px; nav {display: flex; height: 40px Background-color: # f0f0f0; line-height: 40px; text-align: center; a {flex: 1; cursor: pointer; transition: all 300ms; & .active {background-color: # 66f; font-weight: bold Color: # fff;} div {flex: 1; ul {--tab-index: 0;-- tab-width: calc (var (--tab-count) * 100%) -- tab-move: calc (var (--tab-index) / var (--tab-count) *-100%); display: flex; flex-wrap: nowrap; width: var (--tab-width); height: 100%; transform: translate3d (var (--tab-move), 0,0); transition: all 300ms } li {display: flex; justify-content: center; align-items: center; flex: 1; background-color: var (--bg-color); font-weight: bold; font-size: 20px; color: # fff } exportdefault {data () {return {index: 0, list: ["# f66", "# 09f", "# 3c9"]};}, methods: {select (I) {this.index = I This.$refs.tabs.style.setProperty ("--tab-index", I);}; source code links are available at the end of the article

Defined above-- tab-index represents the current index of Tab. By resetting the value of-- tab-index when you click the button, you can display the specified Tab in the position you move without operating DOM. Moving without operating DOM is because-- tab-move is defined, and the relationship between-- tab-index and-- tab-move is calculated by calc (), thus manipulating transform: translate3d () to move.

In addition, defined above-bg-color represents the background color of Tab, which is also a relatively concise way of template assignment, which is always better than writing. If multiple CSS attributes rely on a variable assignment, then it is more convenient to use "CSS variable" assignment to style, those CSS attributes can be calculated and assigned in the CSS file, which can help JS share some of the attribute calculation work.

Of course, this tag navigation bar can also be realized through pure CSS. Interested students can take a look at the pure CSS tag navigation bar in the author's previous article.

Suspension tracking button

Through several chestnuts to practice the use of "CSS variable" in CSS and JS, I believe you have mastered its usage and skills. I have seen a cool mouse levitation effect on a website before, which seems to be realized by using "CSS variable". The author also uses "CSS variable" to realize it from memory.

In fact, the idea is relatively simple, first layout and coloring the button, then use pseudo elements to mark the position of the mouse, define-x and-y represent the coordinates of pseudo elements in the button, get mouse offsetLeft and offsetLeft on the button through JS to assign values to-x and-y, then add radial gradient background color to pseudo elements, and then complete, a cool mouse suspension tracking effect was born.

Use the CSS variable to make your CSS more attractive. Track-btn {display: block; overflow: hidden; border-radius: 100px; width: 400px; height: 50px; background-color: # 66f; line-height: 50px; cursor: pointer; font-weight: bold; font-size: 18px; color: # fff; span {position: relative } &:: before {- size: 0; position: absolute; left: var (--x); top: var (--y); width: var (--size); height: var (--size); background-image: radial-gradient (circle closest-side, # 09f, transparent); content: "" Transform: translate3d (- 50%,-50%, 0); transition: all 200ms ease;} &: hover::before {--size: 400px;}} exportdefault {name: "track-btn", methods: {move (e) {const x = e.pageX-e.target.offsetLeft Const y = e.pageY-e.target.offsetTop; e.target.style.setProperty ("- x", `$ {x} px`); e.target.style.setProperty ("--y", `$ {y} px`);}}; source code links are available at the end of the article

In fact, it can be combined with mouse events to achieve more cool effects, such as animation association, event response and so on. There is no impossible, only unexpected, give full play to your imagination.

I saw a nice chestnut and a floating parallax button on CodePen before, and the specific code involves some knowledge of 3D transformation. After reading the source code, I also realized it according to its idea. By the way, I improved the code slightly and encapsulated it into a Vue component, which was stored in the sample code of this courseware. Feel that the recorded GIF is a little awkward, the display effect is not very good, interested students can download this courseware sample code, run to see the effect.

Compatible

For modern browsers, the compatibility of "CSS variable" is actually quite good, so you can rest assured to use it. After all, this is a time for rapid iteration among major browser manufacturers, and products account for a large proportion of user experience, so try something new boldly when conditions permit, and don't be constrained by some of the so-called specifications in the past.

Ask how many people are willing to maintain IE6~IE9 compatibility, if the user experience of a product is limited by the suppression of ancient browsers (except perhaps government Web applications and financial Web applications), I believe this product will not go very far.

This is the end of the content of "how to use CSS variables to achieve heartbeat effect". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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