2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Vue3页面内跳转锚点-scrollIntoView()

Vue3页面内跳转锚点-scrollIntoView()

时间:2018-09-07 02:11:36

相关推荐

Vue3页面内跳转锚点-scrollIntoView()

scrollIntoView()

scrollIntoView()方法将调用它的元素滚动到浏览器窗口的可见区域。

element.scrollIntoView(); // 等同于element.scrollIntoView(true)element.scrollIntoView(alignToTop); //布尔参数。接受布尔值主要还是为了兼容不支持平滑滚动(老版)的浏览器element.scrollIntoView(scrollIntoViewOptions); //对象参数

alignToTop

当传入参数true时,相当于{behavior: 'auto', block: 'start', inline: 'nearest'}当传入参数false时,相当于{behavior: 'auto', block: 'end', inline: 'nearest'}

当未传入参数时,默认值为:{behavior: 'auto', block: 'start', inline: 'nearest'}

scrollIntoViewOptions,一个包含下列属性的对象。

behavior定义过渡动画,默认值为auto

auto,表示没有平滑的滚动动画效果。smooth,表示有平滑的滚动动画效果。

block定义垂直方向的对齐,默认值为start

start,表示顶端对齐。center,表示中间对齐。end,表示底端对齐。

nearest

如果元素完全在视口内,则垂直方向不发生滚动。如果元素未能完全在视口内,则根据最短滚动距离原则,垂直方向滚动父级容器,使元素完全在视口内。

inline定义水平方向的对齐,默认值为nearest

start,表示左端对齐。center,表示中间对齐。end,表示右端对齐。

nearest

如果元素完全在视口内,则水平方向不发生滚动。如果元素未能完全在视口内,则根据最短滚动距离原则,水平方向滚动父级容器,使元素完全在视口内。

效果图:

示例代码:

<template><div class="box"><div class="left"><p @click="test('id1')">第一段内容</p><p @click="test('id2')">第二段内容</p><p @click="test('id3')">第三段内容</p></div><div class="right"><div class="content" id="id1">我是第一段内容</div><div class="content" id="id2">我是第二段内容</div><div class="content" id="id3">我是第三段内容</div></div></div></template><script setup lang="ts">const test = (data: any) => {document?.getElementById(data)?.scrollIntoView({behavior: "smooth", //smooth:平滑,auto:直接定位block: "start",inline: "start",});};</script><style scoped lang="scss">.box {width: 50vw;height: 50vh;display: flex;overflow: hidden;border: 1px solid gray;.left {width: 100px;height: 100%;border-right: 2px solid gray;p {height: 40px;width: 100%;display: flex;align-items: center;justify-content: center;cursor: pointer;border: 1px solid #ccc;}}.right {flex: auto;overflow: auto;.content {width: 100%;height: 1000px;border-top: 2px solid blue;padding: 20px;box-sizing: border-box;}}}</style>

a标签锚点定位

无平滑效果。需要平滑的话用上面的方式

<template><div class="box"><div class="left"><a href="#id1">第一段内容</a><a href="#id2">第二段内容</a><a href="#id3">第三段内容</a></div><div class="right"><div class="content" id="id1">我是第一段内容</div><div class="content" id="id2">我是第二段内容</div><div class="content" id="id3">我是第三段内容</div></div></div></template><script setup lang="ts"></script><style scoped lang="scss">.box {width: 50vw;height: 50vh;display: flex;overflow: hidden;border: 1px solid gray;scroll-behavior: smooth;.left {width: 100px;height: 100%;border-right: 2px solid gray;a {height: 40px;width: 100%;display: flex;align-items: center;justify-content: center;cursor: pointer;border: 1px solid #ccc;}}.right {flex: auto;overflow: auto;.content {width: 100%;height: 1000px;border-top: 2px solid blue;padding: 20px;box-sizing: border-box;}}}</style>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。