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

Hand tearing red and black trees 2020-11-11 23:28:23
double small black box cool


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]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple