在scrollIntoView()方法基础上如何加入滚动动画
时间: 2023-10-13 14:16:21 浏览: 45
要给 `scrollIntoView()` 方法添加滚动动画,你可以使用 `window.requestAnimationFrame()` 方法来实现平滑的滚动效果。
以下是添加动画的示例代码:
```javascript
function smoothScrollIntoView(target) {
const scrollHeight = window.scrollY;
const targetTop = target.getBoundingClientRect().top;
const offsetTop = targetTop + scrollHeight;
const duration = 1000;
const startTime = performance.now();
function scroll() {
const elapsed = performance.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
const ease = progress => progress < 0.5 ? 2 * progress * progress : 1 - 2 * (1 - progress) * (1 - progress);
window.scrollTo(0, scrollHeight + offsetTop * ease(progress));
if (progress < 1) {
window.requestAnimationFrame(scroll);
}
}
window.requestAnimationFrame(scroll);
}
```
在这个函数中,我们首先获取当前页面的滚动高度和目标元素到顶部的距离。然后,我们定义了动画的持续时间和开始时间,并在 `scroll()` 函数中计算出动画进度和缓动函数。最后,我们使用 `window.scrollTo()` 方法来平滑滚动到目标元素的位置。
你可以像这样调用 `smoothScrollIntoView()` 方法:
```javascript
const targetElement = document.getElementById('target');
smoothScrollIntoView(targetElement);
```
这将会平滑滚动到 ID 为 `target` 的元素的位置。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)