const el = document.getElementById('my-element')
window.scrollTo({
top: el.offsetTop,
behavior: 'smooth'
})
```
window.scrollTo(0, 0);
```
document.documentElement.scrollTop = 0;
3.设置了 overflow ,怎么将页面的 某个内容滚动到顶部
<template>
<div class="container" ref="container" style="overflow: auto;"> <!-- 页面内容 -->
</div>
<button @click="scrollToTop">返回顶部</button>
</template>
<script>
export default {
methods:
{
scrollToTop() {
const container = this.$refs.container;
container.querySelector('.content').scrollIntoView({ behavior: 'smooth' });
}
}
}
</script>
- 插件 scroll-into-view-if-needed
import scrollIntoView from 'scroll-into-view-if-needed'
const content2 = this.$refs.content2;
scrollIntoView(content2, {
scrollMode: 'if-needed',
block: 'start',
inline: 'start',
})