当前位置:网站首页>js实现页面或DOM元素平滑滚动
js实现页面或DOM元素平滑滚动
2022-07-27 15:56:00 【V_AYA_V】
在前端开发页面的工作中,经常会遇到点击导航栏页面滚动到某一指定区域的需求,直接使用window.scroll或者window.scrollTo方法可以实现该需求,但是现实场景中我们希望滚动更加平滑,并且我们希望不仅仅是window能滚动,在某一个设置了overflow-y:scroll属性的div中也能滚动到某一位置。在此,我们以在vue中的实际场景为例:
1.window.requestAnimationFrame()
window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行。使用该方法能够最大限度的利用浏览器的刷新频率触发回调函数,这样在触发滚动事件的时候就可以动态设置滚动条高度,实现平滑滚动的视觉效果。具体文档可参见MDN关于window.requestAnimationFrame()的介绍
2.封装公共的方法
// 获取当前滚动的高度 Dom为目标元素
const getScrollTop = function (Dom) {
return Dom.scrollTop;
};
// 设置滚动条
const setScrollTo = function (Dom, value) {
Dom.scrollTo(0, value);
return value;
};
3.平滑滚动smoothScroll方法实现
const smoothScroll = function (Dom, to, duration) {
if (duration < 0) {
setScrollTo(Dom, to);
return;
}
let diff = to - getScrollTop(Dom);
if (diff === 0) return;
let step = (diff / duration) * 10;
requestAnimationFrame(function () {
if (Math.abs(step) > Math.abs(diff)) {
setScrollTo(Dom, getScrollTop(Dom) + diff);
return;
}
setScrollTo(Dom, getScrollTop(Dom) + step);
if ((diff > 0 && getScrollTop(Dom) >= to) || (diff < 0 && getScrollTop(Dom) <= to)) {
return;
}
smoothScroll(Dom, to, duration - 20);
});
};
4.完整代码
let requestAnimationFrame = (function () {
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
}
);
})();
// 获取当前滚动的高度
const getScrollTop = function (Dom) {
return Dom.scrollTop;
};
// 设置滚动条
const setScrollTo = function (Dom, value) {
Dom.scrollTo(0, value);
return value;
};
// 滚动
const smoothScroll = function (Dom, to, duration) {
if (duration < 0) {
setScrollTo(Dom, to);
return;
}
let diff = to - getScrollTop(Dom);
if (diff === 0) return;
let step = (diff / duration) * 10;
requestAnimationFrame(function () {
if (Math.abs(step) > Math.abs(diff)) {
setScrollTo(Dom, getScrollTop(Dom) + diff);
return;
}
setScrollTo(Dom, getScrollTop(Dom) + step);
if ((diff > 0 && getScrollTop(Dom) >= to) || (diff < 0 && getScrollTop(Dom) <= to)) {
return;
}
smoothScroll(Dom, to, duration - 20);
});
};
export default {
getScrollTop,
setScrollTo,
smoothScroll,
};
本实例没有考虑太多的兼容问题,但是总体思想应该是正确的,在谷歌(86.0.4240.198)正式版本上测试没有问题。后续遇到兼容问题再来补充。
------------------------2021.1.26更新-------------------------
推荐两个方法库:
smooth scroll behavior polyfill
jump.js
边栏推荐
- Wechat applet realizes location map display and introduces map map without navigation
- 【Codeforces】 B. Make it Divisible by 25
- Convolutional neural network -- Introduction to FPN (feature pyramid networks)
- Fast parsing combined with Huatu document encryption software
- 2022 safety officer-a certificate examination questions and online simulation examination
- How difficult the interview is! I was forced to survive the six rounds of interview of ant financial! Almost out (interview resumption)
- 运行loam_velodyne实时建图
- Numpy array matrix operation
- Likeshop takeout ordering system "100% open source without encryption"
- 工信部再治数据安全,网易易盾“隐私合规”守住企业经营底线
猜你喜欢

In the fourth week of July, Yidun business risk control focused on the supreme law to regulate app's forcible request for personal information

微信小程序 实现位置地图显示,引入map地图,不含导航

Convolutional neural network -- Translation of yolov1 thesis

How to resolve the public domain name to the intranet IP server -- quickly resolve the domain name and map the Internet access

Wechat applet realizes location map display and introduces map map without navigation
![[user article] examples of P4 consolidation practice guide disassemble resolve](/img/84/503fc057ce642038f693b38be69bc0.png)
[user article] examples of P4 consolidation practice guide disassemble resolve

WebDriverException( selenium.common.exceptions.WebDriverException: Message: ‘chromedriver‘ executabl

笔试缺考者入围教师招聘面试?河南祥符:个别考生成绩统计错误

类的六大关系——依赖和关联的区别

The global cloud market is growing rapidly, and data security has entered a strong regulatory era of rule of law
随机推荐
Run loam_ Velodyne real-time mapping
golang chan实现互斥锁
【cf】#681 A. Kids Seating (Div. 2, based on VK Cup 2019-2020 - Final)
Convolutional neural network -- SSD thesis translation
Establishing SSL connection without server‘s identity verification is not recommended
JDBC connection database reading foreground cannot display data
工信部再治数据安全,网易易盾“隐私合规”守住企业经营底线
Code compliance: five reasons why developers use helix QAC
Telecommuting can be easily realized in only three steps
Kubernetes 1.24 high availability cluster binary deployment
查找表中多余重复记录并删除保留最小一个
Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?
Notes on standardized management of "ancestral warehouse" of meituan meal
多线程实现循环
MySQL adds users and grants query only permission
hutool- 数组工具
【Codeforces】 B. Make it Divisible by 25
知物由学 | APP大瘦身,新一代AAB框架下的安全加固之道
wallys/DR882-Qualcomm-Atheros-QCA9882-2T2R-MIMO-802.11ac-Mini-PCIe-Wi-Fi-Module-5G-high-power.
Help, boost and take responsibility, the new value and significance of the 6th Tuba rabbit 718 national home decoration Festival