锚点定位更平滑css实现scroll-behavior

2019-05-206919次阅读滚动

CSS属性scroll-behavior为一个滚动框指定滚动行为,其他任何的滚动,例如那些由于用户行为而产生的滚动,不受这个属性的影响。在html根元素中指定这个属性时,将适用于整个视窗口。在某个元素上指定这个属性时不会传播到视口之外。有的用户代理可能会忽略这个属性。

语法

.module {  scroll-behavior: [ auto | smooth ]; }

该scroll-behavior属性接受两个值,基本上可以关闭和打开平滑滚动功能。

auto (默认值):此值允许滚动框内元素之间的突然跳转。

smooth:正如其名称平滑滚动,滚动框通过一个用户代理定义的时间段使用定义的时间函数来实现平稳的滚动,用户代理平台应遵循约定,如果有的话。

浏览器兼容

经测试IOS、Android移动端支持还不错。

使用场景

tab切换

其实也是通过#锚点实现的。

HTML代码:

<nav>
  <a href="#1">1</a>
  <a href="#2">2</a>
  <a href="#3">3</a>
</nav>
<div class="scrolling-box">
  <section id="1">This is the first section</section>
  <section id="2">This is the second section</section>
  <section id="3">This is the third section</section>
</div>

CSS代码:

body {
  background-color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
nav {
  background-color: #000;
  display: block;
  padding: 1em 0;
  text-align: center;
  width: 200px;
}
nav a {
  color: #fff;
  margin: 0 1em;
  text-decoration: none;
}

.scrolling-box {
  background-color: #eaeaea;
  display: block;
  height: 200px;
  overflow-y: scroll;
  scroll-behavior: smooth;
  text-align: center;
  width: 200px;
}
section {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

你也可以通过css3再把滚动条美化一下那就更好啦。

锚点滚动

原生#锚点滚动是特别生硬,就是auto突然跳转。当你给html根元素添加

html {
  scroll-behavior: smooth;
}

你会发现整个世界都是特别的美好和谐。

上一篇: 隐藏原生HTML5视频控件  下一篇: 为什么大部分CSS自定义属性放在:root中  

锚点定位更平滑css实现scroll-behavior相关文章