当前位置:网站首页>平滑滚动到元素
平滑滚动到元素
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));
});边栏推荐
- Apaas low code platform (I) | leave complexity to yourself and simplicity to users
- 【HarmonyOS议题资料下载】HDD杭州站·线下沙龙专注应用创新 展现鸿蒙生态魅力
- Arm TZ hardware support
- Practice of microservice in solving Library Download business problems
- Niuke brush questions - MySQL series
- 关于:获取当前客户端登录的域控
- [virtual machine data recovery] data recovery of XenServer virtual machine unavailable due to unexpected power failure
- [ffmpeg] add timestamp summary to video files
- What kind of security problems will the server encounter?
- Summary of common interview questions of operating system, including answers
猜你喜欢

Pointpillars: fast encoders for object detection from point clouds reading notes

Mobile phone \ landline call forwarding setting method

留存收益率计算公式

LeetCode 练习——剑指 Offer II 005. 单词长度的最大乘积
HTTP cache browser cache that rabbits can understand

We were tossed all night by a Kong performance bug

IT系统为什么需要可观测性?

Rare discounts on Apple's official website, with a discount of 600 yuan for all iphone13 series; Chess robot injured the fingers of chess playing children; Domestic go language lovers launch a new pro

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

Why does it system need observability?
随机推荐
QT Foundation Day 1 (1) QT, GUI (graphical user interface) development
Broadcast voice H5 speechsynthesisutterance
Error in render: “TypeError: data.slice is not a function“
ECCV 2022 | complete four tracking tasks at the same time! Unicorn: towards the unification of target tracking
[OBS] solve the problem of OBS pushing two RTMP streams + timestamp
【HCIE安全】双机热备-主备备份
Leetcode array class
【HarmonyOS议题资料下载】HDD杭州站·线下沙龙专注应用创新 展现鸿蒙生态魅力
Test cases should never be used casually, recording the thinking caused by the exception of a test case
Rare discounts on Apple's official website, with a discount of 600 yuan for all iphone13 series; Chess robot injured the fingers of chess playing children; Domestic go language lovers launch a new pro
腾讯为什么没能造创造出《原神》这样的游戏
Props with type Object/Array must...
SPI configuration
Serial port communication failure
In the era of Web3.0, the technical theory of implementing a DAPP based on P2P DB
IT系统为什么需要可观测性?
详解西部数据SMR叠瓦式硬盘的190二级编译器(译码表)模块
How to implement Devops with automation tools | including low code and Devops application practice
Devsecops, speed and security
Niuke brush questions - MySQL series