body 挂 scroller-hover 类,全局滚动条默认隐藏、悬停显形
我们再写项目的时候 UI 会设计一些规范,比如滚动条的。他们的设计规范是:默认有滚动条但不展示滚动条,当鼠标划上去才展示滚动条。这个跟我们的浏览器滚动条样式有冲突,我们默认的滚动条样式是默认展示出来的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.main {
height: 300px;
overflow-y: auto;
border: 1px solid red;
}
.item {
height: 40px;
width: 100%;
background-color: #df1e1e;
margin-bottom: 20px;
color: black;
}
</style>
</head>
<body>
<div class="main">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
</div>
</body>
</html>
可见默认是展示的。我们要做的就是要其默认不展示,鼠标滑上去再展示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.main {
height: 300px;
overflow-y: auto;
border: 1px solid red;
}
.item {
height: 40px;
width: 100%;
background-color: #df1e1e;
margin-bottom: 20px;
color: black;
}
:root {
--color-border-1: #888;
/* 深灰色 - 滑块激活状态 */
--color-border-2: #ddd;
/* 浅灰色 - 滑块默认悬停状态 */
}
body.scroller-hover::-webkit-scrollbar,
body.scroller-hover *::-webkit-scrollbar {
width: 6px;
height: 6px;
}
body.scroller-hover::-webkit-scrollbar-corner,
body.scroller-hover *::-webkit-scrollbar-corner {
background-color: rgba(0, 0, 0, 0);
}
body.scroller-hover:hover::-webkit-scrollbar-track-piece,
body.scroller-hover *:hover::-webkit-scrollbar-track-piece {
background-color: rgba(0, 0, 0, 0);
border-radius: 6px;
}
body.scroller-hover:hover::-webkit-scrollbar-thumb,
body.scroller-hover *:hover::-webkit-scrollbar-thumb {
background-color: var(--color-border-2);
border-radius: 6px;
}
body.scroller-hover:hover::-webkit-scrollbar-thumb:active,
body.scroller-hover:hover::-webkit-scrollbar-thumb:hover,
body.scroller-hover *:hover::-webkit-scrollbar-thumb:active,
body.scroller-hover *:hover::-webkit-scrollbar-thumb:hover {
background-color: var(--color-border-1);
}
</style>
</head>
<body class="scroller-hover">
<div class="main">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
</div>
</body>
</html>
以上我们实现了滚动条的全局优化。请注意 body 的类名配置,这样全局的所有滚动条均会按照此逻辑展示。