- https://segmentfault.com/a/1190000041886147
Element 方法 scrollIntoView:滚动父级容器,使得元素出现在视口。
- 参数
type alignToTop = boolean
type scrollIntoViewOptions = {
behavior: 'auto' | 'smooth'
block: 'start' | 'center' | 'end' | 'nearest'
inline: 'start' | 'center' | 'end' | 'nearest'
}
interface Element {
scrollIntoView(arg?: alignToTop | scrollIntoViewOptions): void
}
使用
- 页面内锚链接跳转到指定区域
//js
// 点击跳转
function GOstep(dom) {
document.getElementById(dom) .scrollIntoView({ behavior: 'smooth' })
}
//html step1是要跳转到的目标标签的id
<li @click="GOstep('step1')"></li>
- 检测页面滚动
// vue3 setup组合式写法
<script setup>
import {ref,reactive,onMounted,onUpdated,onUnmounted} from 'vue'
onMounted(async ()=>{
// 添加监听事件
window.addEventListener("scroll", onScrollW);
})
function onScrollW(){
let scrTopValue= document.documentElement.scrollTop || document.body.scrollTop;
if(scrTopValue){
...
}
</script>