当前位置:网站首页>平滑滚动到元素
平滑滚动到元素
2022-07-26 20:31:00 【紫微前端】
正如滚动到元素帖子中提到的,我们可以通过传递平滑滚动到给定元素behavior: 'smooth':
ele.scrollIntoView({ behavior: 'smooth' });或将 CSS 属性scroll-behavior应用于目标元素:
scroll-behavior: smooth;导航由一些a元素组成:
<a href="#section-1" class="trigger"></a>
<a href="#section-2" class="trigger"></a>
...
<div id="section-1">...</div>
<div id="section-2">...</div>单击链接会将页面滚动到可由href属性确定的特定元素。
const triggers = [].slice.call(document.querySelectorAll('.trigger'));
triggers.forEach(function (ele) {
ele.addEventListener('click', clickHandler);
});该clickHandler函数处理click导航元素的事件。它根据href属性确定目标部分。请注意,我们将自己滚动到目标部分,因此默认操作将被忽略:
const clickHandler = function (e) {
// Prevent the default action
e.preventDefault();
// Get the `href` attribute
const href = e.target.getAttribute('href');
const id = href.substr(1);
const target = document.getElementById(id);
scrollToTarget(target);
};scrollToTarget如果您还没有看到该功能,请不要担心。顾名思义,该函数会将页面滚动到 given target。
window.scrollTo({ top, left, behavior: 'smooth' });滚动到给定目标
window.scrollTo(0, y)wherey指示从页面顶部到目标的距离。- 起点是当前的y轴偏移量,
window.pageYOffset - 终点是目标的顶部距离。它可以检索为
target.getBoundingClientRect().top - 持续时间是毫秒数。您可以将其更改为可配置选项,但在本文中,它设置为 800。
const duration = 800;
const scrollToTarget = function (target) {
const top = target.getBoundingClientRect().top;
const startPos = window.pageYOffset;
const diff = top;
let startTime = null;
let requestId;
const loop = function (currentTime) {
if (!startTime) {
startTime = currentTime;
}
// Elapsed time in miliseconds
const time = currentTime - startTime;
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * percent);
if (time < duration) {
// Continue moving
requestId = window.requestAnimationFrame(loop);
} else {
window.cancelAnimationFrame(requestId);
}
};
requestId = window.requestAnimationFrame(loop);
};loop在下一次绘制发生之前执行该函数。第一次,startTime将被初始化为当前时间戳(currentTime)。const time = currentTime - startTime;根据经过的时间和持续时间,很容易计算我们移动的百分比数,然后滚动到该位置:
// `percent` is in the range of 0 and 1
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * percent);最后,如果还有剩余时间,我们继续循环。否则,我们取消最后一个请求:
if (time < duration) {
// Continue moving
requestId = window.requestAnimationFrame(loop);
} else {
window.cancelAnimationFrame(requestId);
}自定义动画
easeInQuad动画:const easeInQuad = function(t) {
return t * t;
};
const loop = function(currentTime) {
...
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * easeInQuad(percent));
});边栏推荐
- 我们被一个 kong 的性能 bug 折腾了一个通宵
- 苹果官网罕见打折,iPhone13全系优惠600元;国际象棋机器人弄伤对弈儿童手指;国内Go语言爱好者发起新编程语言|极客头条
- Arm TZ hardware support
- Multivariable time series prediction using LSTM -- problem summary
- Redis interview questions
- [HCIA security] user authentication
- [download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng
- Introduction of JDBC
- There are six ways to help you deal with the simpledateformat class, which is not a thread safety problem
- js中join方法
猜你喜欢

How to configure the legendary SF lander to automatically read the list without a network

Daily practice ----- there is a group of students' grades. Arrange them in descending order. To add a student's grade, insert it into the grade sequence and keep the descending order

【HarmonyOS议题资料下载】HDD杭州站·线下沙龙专注应用创新 展现鸿蒙生态魅力

js中join方法

Go+mysql+redis+vue3 simple chat room, the sixth bullet: use vue3 and element plus to call the interface

Remember the idea of solving the problem of invalid bound statement xxxxx once

Devsecops, speed and security

After chatting with byte programmers with a monthly salary of 3W, I realized that I had been doing chores

腾讯为什么没能造创造出《原神》这样的游戏

Test cases should never be used casually, recording the thinking caused by the exception of a test case
随机推荐
Web3.0 时代,基于P2PDB实现一款Dapp的技术理论
How to block the legendary GEE engine version? Close player account tutorial through script + engine
JVM学习----内存结构----程序计数器&虚拟机栈&本地方法栈&堆&方法区
[must read new] Keya valuation analysis of University of technology, heating energy-saving products
[question] browser get request with token
CFdiv1+2-Pathwalks-(树状数组+线性dp)
09_ UE4 advanced_ Enter the next level and reserve the blood volume
What are the characteristics of low code tools? The two development tracks of low code that can be seen by discerning people!
idea中设置核心配置文件的模板
ECCV 2022 | 同时完成四项跟踪任务!Unicorn: 迈向目标跟踪的大统一
Difference between redis hash and string
使用 LSTM 进行多变量时间序列预测--问题汇总
What kind of security problems will the server encounter?
ECCV 2022 | complete four tracking tasks at the same time! Unicorn: towards the unification of target tracking
js中join方法
Soft test --- database (1) database foundation
洛谷-线段覆盖-(区间排序问题总结)
Line detection based on Hough transform (matlab)
立即报名:7 月 29 日推荐系统峰会 2022
【HCIA安全】双向NAT