从前我们在网页中会需要内容定位,或者返回顶部之类的功能,通常使用锚点来实现,但是页面跳转太过生硬,用户体验不够,于是会通过一大串的js来实现平滑滚动的效果,近两年出现了一些新的属性可以很方便的完成这种交互,很大程度的减小了开发难度。
<li class="nav703548"><a style="cursor: pointer;" onclick="javascript:document.getElementById('area_3').scrollIntoView({ behavior:'smooth' })"><span>支持</span></a></li>
<li class="nav703550"><a style="cursor: pointer;" onclick="javascript:document.getElementById('area_4').scrollIntoView({ behavior:'smooth' })"><span>优势</span></a></li>
<li class="nav703550"><a style="cursor: pointer;" onclick="javascript:document.getElementById('area_2').scrollIntoView({ behavior:'smooth' })"><span>合作流程</span></a></li>
<li class="nav703551"><a style="cursor: pointer;" onclick="javascript:document.getElementById('footer_0').scrollIntoView({ behavior:'smooth' })"><span>联系我们</span></a></li>
scrollIntoView()有三个参数:
behavior 表示滚动方式。auto 表示使用当前元素的 scroll-behavior 样式。instant 和 smooth
表示 直接滚到底 和 使用平滑滚动。
block 表示块级元素排列方向要滚动到的位置。对于默认的 writing-mode: horizontal-tb
来说,就是竖直方向。start 表示将视口的顶部和元素顶部对齐;center 表示将视口的中间和元素的中间对齐;end表示将视口的底部和元素底部对齐;nearest 表示就近对齐。
inline 表示行内元素排列方向要滚动到的位置。对于默认的 writing-mode: horizontal-tb 来说,就是水平方向。其值与 block 类似
使用scrollIntoView的场景:
想页面增加内容时,让页面滚动最下面添加的位置
聊天向上显示最新对话
回到顶部
document.documentElement.scrollIntoView({
behavior: “smooth”,
block: “end”,
inline: “nearest”
});