编程知识 cdmana.com

Double 11 small black box is cool? Let's use CSS variables to improve it!

Preface

The pair that just passed 11 What websites have everyone gone shopping ? No matter which website you go to , It is estimated that tmall is indispensable , I found such an interesting phenomenon when visiting tmall :

Although this effect is still relatively common , But there's one detail that's different , For example, let's take a look at a common header The effect that fades as the window scrolls :

What's the difference , The normal version is completely transparent at first , As the window scrolls, it shows up slowly , It's about control opacity Transparency attribute to achieve .

And the little black box version had a gradient from the beginning , Gradient to nearly translucent , It looks more elegant in this way , But it looks like it's just a nice gradient when you get into the page before you scroll , When rolling, the behavior is similar to that when we rely on transparency .

What we need to improve is to use the rolling distance to control background-position, As the window scrolls , Will slowly change the gradient of the gradient to control the rendering effect .

style

First of all, let's put header Write it out :

header {
      /*  Set a control for the position of the background color CSS Variable , convenient JS control  */
      --position: 100;

      /*  Show child elements at the bottom of the center  */
      display: grid;
      place-items: end center;

      /*  Set to fixed position  */
      position: fixed;

      /*  From the top to the left is 0 */
      top: 0;
      left: 0;

      /*  The width covers the screen  */
      width: 100%;

      /*  Give it the right height  */
      height: 40px;

      /*  White font  */
      color: white;

      /*  font size  */
      font-size: 16px;

      /*  Make the font smaller  */
      font-weight: 100;

      /*  Increase the internal and external changes , Prevent the text from being too low  */
      padding-bottom: 10px;

      /*  Set the transition effect  */
      transition: background-position .2s;

      /*  Black gradient background  */
      background: linear-gradient(black, rgba(148, 88, 88, 0.3) 80%, rgba(0, 0, 0, 0)) 0 calc(var(--position) * 1%) / 100% 300%;
    }

Running results :

You can see that we are header There's a line in it CSS Variable , If you don't know exactly what CSS Variable Please click here , I also use gird To carry out In the middle , Of course, it's not complete In the middle , It's a little bit lower , Because I think the small black box of tmall is made lower and middle .

Overall implementation

And then we started to write JS Code. , Because pure CSS You can't get the scrolling distance of the screen , But in order to make it easier for both sides to interact , We still use CSS Variable , because CSS Variable The improvement is not just about saving CSS Code , As well as reduce CSS Development and maintenance costs play a role .

what's more , The development of many interaction components from the original JS Transferred to CSS In the code , Make component code simpler , At the same time, it makes the visual expression more flexible . —— Zhang Xin Xu

CSS Variable What specific benefits can be brought to us , You can refer to Zhang Xinxu's blog :

《CSS Variable pair JS The improvement and change brought by interactive component development 》

Take a look at CSS Variable How is it with JS interactive :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title> My own little black box with gradient </title>
  <style>
    /*  Clear default style  */
    * { padding: 0; margin: 0 }

    header {
      /*  Set a control for the position of the background color CSS Variable , convenient JS control  */
      --position: 100;

      /*  Show child elements at the bottom of the center  */
      display: grid;
      place-items: end center;

      /*  Set to fixed position  */
      position: fixed;

      /*  From the top to the left is 0 */
      top: 0;
      left: 0;

      /*  The width covers the screen  */
      width: 100%;

      /*  Give it the right height  */
      height: 40px;

      /*  White font  */
      color: white;

      /*  font size  */
      font-size: 16px;

      /*  Make the font smaller  */
      font-weight: 100;

      /*  Increase the internal and external changes , Prevent the text from being too low  */
      padding-bottom: 10px;

      /*  Set the transition effect  */
      transition: background-position .2s;

      /*  Black gradient background  */
      background: linear-gradient(black, rgba(148, 88, 88, 0.3) 80%, rgba(0, 0, 0, 0)) 0 calc(var(--position) * 1%) / 100% 300%;
    }

    main {
      /*  Give it the right height  */
      height: 1000px;
    }
  </style>
</head>
<body>
  <header> Our own little black box </header>
  <main></main>

  <script>
    //  obtain header
    const header = document.getElementsByTagName('header')[0]

    addEventListener('scroll', () => {
      //  Get the offset value 
      const top = document.documentElement.scrollTop

      //  Set a suitable range 
      if (top <= 200) {
        //  Make header The gradient position becomes the calculated gradient position 
        header.style.setProperty('--position', 100 - Math.min(100, top))
      } else {
        //  It's completely opaque in a certain range 
        header.style.setProperty('--position', 0)
      }
    })
  </script>
</body>
</html>

Running results :

Imagine if you don't have to CSS Variable What will become of it :

header.style.backgroundPosition = '0 ' + 100 - Math.min(100, top) + '%'

Although it looks like nothing , But when there are more attributes to control, it's going to be a disaster , And it has to be carried with you all the time CSS Company , image px、%、rem these , It adds unnecessary mental burden to us , It also slows down the efficiency of the program .

It was used CSS Variable After that, you don't have to bring any units , Assign a number directly , So why don't you bring your unit ? The answer lies in calc On the function :

calc( var(--position) * 1%)

Remember you can't use it here JS To write calc Function , stay JS We use +, Because it represents string concatenation , And here the numbers multiply one percent , It becomes a specific percentage , Similarly, if you need other units, you can modify them flexibly according to your specific needs :

calc( var(--position) * 1px)

️ Be careful px The front one 1 Very important , You can't omit !

And it's not necessary to write 1, According to the specific needs, we can also use multiple to :

calc( var(--position) * 6.6rem)

Expand

In fact, from the code and the effects we see in our daily life, we can see that , Basically after rolling for a distance header The transparency is fixed and will not change again , Waste monitoring onscroll event . But you can't cancel listening , Because I don't know when the user will slide to the top again , But this situation is very suitable for another effect :

I forget what this effect is called , In short, it shows something like a progress bar at the top as the user scrolls the page , It is convenient for users to know what kind of position they are in the web page , Look at code :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title> My own little black box with gradient </title>
  <style>
    /*  Clear default style  */
    * { padding: 0; margin: 0 }

    header {
      /*  Setting a control position CSS Variable , convenient JS control  */
      --position: 0;

      /*  Set to fixed position  */
      position: fixed;

      /*  From the top to the left is 0 */
      top: 0;
      left: 0;

      /*  The width covers the screen  */
      width: 100%;

      /*  Give it the right height  */
      height: 10px;

      /*  Set the transition effect  */
      transition: transform .1s;

      /*  Gradient background  */
      background: linear-gradient(to right,#4481eb,#04befe);

      /*  Set the deformation effect  */
      transform: scaleX(var(--position));

      /*  Set the deformation reference point  */
      transform-origin: left;
    }

    main {
      /*  Give it the right height  */
      height: 10000px;

      /*  Gradient background  */
      background: linear-gradient(#30cfd0,#330867)
    }
  </style>
</head>
<body>
  <header></header>
  <main></main>

  <script>
    //  obtain header
    const header = document.getElementsByTagName('header')[0]

    addEventListener('scroll', () => {
      //  Get the offset value 
      const top = document.documentElement.scrollTop

      //  Get the total page height 
      const height = document.documentElement.scrollHeight

      //  Set up CSS Variable 
      if (top > height - document.documentElement.clientHeight - 1) {
        header.style.setProperty('--position', 1)
      } else {
        header.style.setProperty('--position', top / height)
      }
    })
  </script>
</body>
</html>

This article was first published on WeChat public :《 The front end can't learn 》

版权声明
本文为[Hand tearing red and black trees]所创,转载请带上原文链接,感谢

Scroll to Top