2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > web实现置顶 置底功能 聊天页面 锚点 滚动条 vue scrollTop scrollIntoView scrollHeight

web实现置顶 置底功能 聊天页面 锚点 滚动条 vue scrollTop scrollIntoView scrollHeight

时间:2023-02-08 01:51:28

相关推荐

web实现置顶 置底功能 聊天页面 锚点 滚动条 vue scrollTop scrollIntoView scrollHeight

目录

前言1、代码实现3、scrollTop实现置顶置底(方式一)4、scrollIntoView实现置顶置底(方式二)5、总结

前言

在项目中遇到聊天功能,功能涉及置顶和置底知识,由此记录一下实现思路和过程。

1、代码实现

html

<div class="p_b_36" id="idTop"><div><div v-for="item in arr" :key="item.id">{{ item.value }}</div><div id="idBottom"><input v-model="value" type="text" placeholder="请输入内容..." /><span class="padding_6 m_l_8 bac_eee bor_rad_2" @click="sending">发 送</span></div></div><div class="pf cp right_26 bottom_100" @click="setTop">置顶</div><div class="pf cp right_26 bottom_50" @click="setBottom">置底</div></div>

JavaScript

export default {name: 'HelloWorld',props: {msg: String},data() {return {arr: [],value: ''}},created() {this.init();},methods: {// 发送async sending() {let arrLen = this.arr.length,value = this.value;await this.arr.push({id: `id${arrLen + 1}`,value: value});this.setBottom();},// 置底setBottom() {// // 方式一 vue3无响应// let scrollTop = document.body.scrollHeight;// document.documentElement.scrollTop = scrollTop;// 方式二 把该元素的最底部内容显示在可视区域的最底部let idBottom = document.getElementById("idBottom");idBottom.scrollIntoView({block: "end" });},// 置顶setTop() {// 方式一 vue3无响应// document.documentElement.scrollTop = 0;// 方式二 把该元素的最顶部内容显示在可视区域的最顶部let idTop = document.getElementById("idTop");idTop.scrollIntoView({block: "start" });},// 初始化init() {let arr = [];for (let i = 0; i < 86; i++) arr.push({id: `id${i + 1}`,value: `${i + 1}`});this.arr = arr;}}}

style

.pf {position: fixed;}.cp {cursor: pointer;}.right_26 {right: 26px;}.padding_6 {padding: 6px;}.bottom_100 {bottom: 100px;}.bottom_50 {bottom: 50px;}.p_b_36 {padding-bottom: 36px;}.m_l_8 {margin-left: 8px;}.bac_eee {background-color: #eeeeee;}.bor_rad_2 {border-radius: 2px;}

3、scrollTop实现置顶置底(方式一)

基本介绍

Element.scrollTop属性可以获取或设置一个元素的内容垂直滚动的像素数。

一个元素的scrollTop值是这个元素的内容顶部到它的视口可见内容的距离的度量。当一个元素的内容没有产生垂直方向的滚动条,那么它的scrollTop值为0

在使用显示比例缩放的系统上,scrollTop可能会提供一个小数值。

设置值规范

如果一个元素不能被滚动,scrollTop将被设置为0

设置scrollTop的值小于0scrollTop被设为0

如果设置了超出这个容器可滚动的值,scrollTop会被设为最大值。

4、scrollIntoView实现置顶置底(方式二)

简单介绍

Element接口的scrollIntoView()方法会滚动元素的父容器,使被调用scrollIntoView()的元素对用户可见。

参数

布尔值

如果为true,元素的顶端将和其所在滚动区的可视区域的顶端对齐,等价于{ block: "start", inline: "nearest" },这是这个参数的默认值。

如果为false,元素的底端将和其所在滚动区的可视区域的底端对齐,等价于{ block: "end", inline: "nearest" }

属性对象

behavior定义动画过渡效果,autosmooth之一,默认为auto

block定义垂直方向的对齐,startcenterendnearest之一,默认为start

inline定义水平方向的对齐,startcenterendnearest之一,默认为nearest

注意

此元素可能不会完全滚动到顶端或底端,这取决于其他元素的布局情况。

5、总结

1、方式一在vue3中无响应,不报错,功能也没有实现。

2、方式二可能在某些场景不适用,但兼容性会比方式一好一些。

3、以上两种方式属于原生方法和属性,所以不区分框架与原生情况。

4、置底功能适用于聊天页面,置顶功能适用于有滚动条需要返回顶部的功能。

5、方式一使用设置滚动条的方式实现;方式二使用锚点的方式实现。

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