我们之前利用 a 标签的锚点功能,能让页面滚动到指定位置,但是存在顿挫感,使用scroll-behavior: smooth;
可以让滚动变得丝滑。
CSS 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .box1 { background-color: aqua; width: 1000px; height: 600px; margin: 80px 20px; } .box2 { background-color: rgb(0, 255, 13); width: 1000px; height: 600px; margin: 80px 20px; } .box3 { background-color: rgb(227, 154, 177); width: 1000px; height: 600px; margin: 80px 20px; } .slidebar { position: fixed; top: 50%; right: 0; transform: translateY(-50%); } .slidebar > a { width: 80px; height: 80px; display: flex; justify-content: center; align-items: center; } .slidebar > a:first-child { background-color: aqua; } .slidebar > a:nth-child(2) { background-color: rgb(0, 255, 13); } .slidebar > a:last-child { background-color: rgb(227, 154, 177); } html { scroll-behavior: smooth; } </style> </head> <body> <div class="box1" id="box1">服饰</div> <div class="box2" id="box2">家电</div> <div class="box3" id="box3">生鲜</div> <div class="slidebar"> <a href="#box1">服饰</a> <a href="#box2">家电</a> <a href="#box3">生鲜</a> </div> </body> </html>
|
但是 scroll-behavior 的兼容性会很差,比如在移动端 ios 基本不支持,我们也可以用 JS 来实现
JS 实现
1 2 3
| target.scrollIntoView({ behavior: "smooth", });
|