凡是需要滚动的地方都加一句scroll-behavior:smooth就好了!
例如:在PC浏览器中,网页默认滚动是在<html>标签上的,移动端大多数在<body>标签上,于是,可以加上这么一句:
html, body{scroll-behavior:smooth;}
JS scrollIntoView与平滑滚动
我们随便打开一个又连接的页面,把首个连接滚动到屏幕外,然后控制台输入类似下面代码,我们就可以看到页面平滑滚动定位了:
document.links[0].scrollIntoView({ behavior:"smooth" })
如果我们的网页已经通过css设置了scroll-behavior:smooth生命,则我们直接执行target.scrollIntoView()方法就会有平滑滚动,无需再额外设置behavior参数。例如:
document.links[0].scrollIntoView();
js平滑滚动向下兼容处理
if(typeof window.getComputedStyle(document.body).scrollBehavior=='undefined'){ //传统的JS平滑滚动处理代码。。。 }
可以使用张鑫旭大神自己写的方法:
/** @description 页面垂直平滑滚动到指定滚动高度 @author zhangxinxu(.com) */ var scrollSmoothTo = function (position) { if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { return setTimeout(callback, 17); }; } // 当前滚动高度 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 滚动step方法 var step = function () { // 距离目标滚动距离 var distance = position - scrollTop; // 目标滚动位置 scrollTop = scrollTop + distance / 5; if (Math.abs(distance) < 1) { window.scrollTo(0, position); } else { window.scrollTo(0, scrollTop); requestAnimationFrame(step); } }; step(); };