<!DOCTYPE html>
<html>
<head>
<style>
.dashed-scroll {
width: 300px;
height: 4px;
margin: 50px auto;
background:
repeating-linear-gradient(
to right,
#000 0%,
#000 50%,
transparent 50%,
transparent 100%
);
background-size: 30px 100%;
animation: scroll 1s linear infinite;
}
@keyframes scroll {
from {
background-position: 0 0;
}
to {
background-position: 30px 0;
}
}
/* 其他方向示例 */
.vertical-scroll {
width: 4px;
height: 200px;
background:
repeating-linear-gradient(
to bottom,
#000 0%,
#000 50%,
transparent 50%,
transparent 100%
);
background-size: 100% 30px;
animation: scroll-vertical 1s linear infinite;
}
@keyframes scroll-vertical {
from {
background-position: 0 0;
}
to {
background-position: 0 30px;
}
}
</style>
</head>
<body>
<!-- 水平滾動(dòng) -->
<div class="dashed-scroll"></div>
<!-- 垂直滾動(dòng) -->
<div class="vertical-scroll"></div>
</body>
</html>
實(shí)現(xiàn)原理:
使用 repeating-linear-gradient 創(chuàng)建重復(fù)的虛線圖案
通過 background-size 控制虛線段的重復(fù)間距
使用 CSS 動(dòng)畫改變 background-position 實(shí)現(xiàn)滾動(dòng)效果
關(guān)鍵點(diǎn)說明:
水平滾動(dòng):漸變方向?yàn)?to right,動(dòng)畫改變 X 軸位置
垂直滾動(dòng):漸變方向?yàn)?to bottom,動(dòng)畫改變 Y 軸位置
通過調(diào)整 background-size 的值可以改變虛線的間隔長(zhǎng)度
修改顏色值(#000)可以改變虛線的顏色
調(diào)整動(dòng)畫時(shí)長(zhǎng)(1s)可以改變滾動(dòng)速度