scroll-behavior 让滚动更顺滑

scroll-behavior 让滚动更顺滑

使用场景

现在查看内容较长的页面时,通常可以在页面的头部或者右侧看到有一个定位导航,这样就能很容易根据导航找到想要的资源。


常见的实现方法是锚点跳转,实现原理是,页面上的id会自动创建一个锚点,同时还会生成一个 hash 表示所处的文档位置。浏览器可以通过 hash 来确定位置,使用的方式一般为:


<a href="#part1">标题一</a>

* 点击的时候,地址栏后会加上一段 # 开头的hash  


Demo

根据上面的方法我们来写一个简单的例子,代码部分如下:


HTML部分

<header>  <a href="#part1">第一屏</a>  <a href="#part2">第二屏</a>  <a href="#part3">第三屏</a>  <a href="#part4">第四屏</a></header>
<section id="part1">这是第一屏内容</section><section id="part2">这是第二屏内容</section><section id="part3">这是第三屏内容</section><section id="part4">这是第四屏内容</section>

CSS部分:

body,p{margin0;padding0;font-family:'Microsoft yahei';}header{    height:40px;    line-height: 40px;    background: #efefef;    text-align: center;    margin-bottom: 10px;}header a{    color:#333;    text-decoration:none;    padding:0 20px;}
section{ width: 100%; height: 500px; line-height: 500px; font-size: 20px; text-align: center; background: #efefef; margin-bottom:5px;}


实现的效果如下:

scroll-behavior 让滚动更顺滑


可以发现浏览器跳转方式很生硬,会直愣愣地跳到指定位置(或者没有找到指定位置会跳到页面最上面),对于用户来说,这个体验非常不友好,下面我们就使用CSS3的scroll-behavior属性来优化一下。


scroll-behavior

MDN上对于scroll-behavior的定义是:

当用户手动导航或者 CSSOM scrolling API 触发滚动操作时,CSS 属性 scroll-behavior 为一个滚动框指定滚动行为,其他任何的滚动,例如那些由于用户行为而产生的滚动,不受这个属性的影响。在根元素中指定这个属性时,它反而适用于视窗。

https://developer.mozilla.org/zh-CN/docs/Web/CSS/scroll-behavior

scroll-behavior的默认值是:auto ,适用于所有的可滚动盒子,非继承属性。


scroll-behavior有两个值:auto和smooth。auto指滚动框立即滚动smooth代表滚动框通过一个用户代理预定义的时长、使用预定义的时间函数,来实现平稳的滚动,用户代理应遵循其平台的约定,如果有的话。


上面的例子里,我们对根元素html使用了scroll-behavior:smooth,滚动效果就会平滑了很多,结果如下:


scroll-behavior 让滚动更顺滑


注意:也可以将其添加到特定元素/滚动容器


浏览器兼容性

scroll-behavior 让滚动更顺滑

chrome高于61;IE不支持;firfox高于36;opera都支持

https://caniuse.com/#search=scroll-behavior


跨浏览器解决方案

对于不支持该scroll-behavior属性的浏览器,您可以使用JavaScript或JavaScript库(如jQuery)来创建适用于所有浏览器的解决方案:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>$(document).ready(function(){  // Add smooth scrolling to all links  $("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior if (this.hash !== "") { // Prevent default anchor click behavior event.preventDefault();
// Store hash var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(hash).offset().top }, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash; }); } // End if });});</script>

以上使用了jQuery库的解决方案

https://www.w3schools.com/howto/howto_css_smooth_scroll.asp



本篇文章来源于微信公众号: TripDesign

UI/UX

这个7月,腾讯CDC与你相约IXDC,不见不散!

2019-7-4 17:38:04

UI/UX

CDC达人 | Hello world !-安正超

2019-7-5 21:36:51

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索