点击按钮滚动轴滑动到指定位置
问题
对话框中有个表单,点击按钮,需要在底部添加一条数据,并让滚动轴滑动到最底部,以便用户直观了解变化。
效果

解决 container.scrollTop = container.scrollHeight - container.clientHeight

/* 添加属性按钮 */
addProp() {
// 确保有 measureAttributeList 属性
if (!this.form.measureAttributeList) {
this.$set(this.form, 'measureAttributeList', [])
}
this.form.measureAttributeList.push({
id: '',
measureUnit: {id: ''}
})
// 让页面滚动条滑动到底部
this.$nextTick(() => {
const container = this.$refs.dialogContent
const { scrollHeight, clientHeight} = container
container.scrollTop = scrollHeight - clientHeight
})
},
由于此处 container 没有内边距,且 content 也没有边框,因此 container.scrollHeight 和 content.clientHeight 的值是一样的。
即有第二种方法: container.scrollTop = content.clientHeight - container.clientHeight。
怎样获取到 content ?


由于 ref="form" 是作用在组件而不是元素上的,因此如果用 this.$refs.form 获取到的是该组件的实例对象,即 dom 元素对象。
要想获取到 content,就要用 $el 获取组件的根元素,即 const content = this.$refs.form.$el。
所以,第二种方法:
...
// 让页面滚动条滑动到底部
this.$nextTick(() => {
const container = this.$refs.dialogContent
const content = this.$refs.form.$el
container.scrollTop = content.clientHeight - container.clientHeight
})
当然建议使用第一种方法。
注意
这里必须要用 this.$nextTick 包裹,否则滚动位置是在空白数据条的上方,即:

总结
scrollTop: 可读可写。滑动滚动条,获取元素滚动条到元素顶部的距离。
scrollHeight:只读。若 container 没有添加 overflow 属性时,container 的像素高度【(content 的高度+内边距+border+外边距)+container的内边距】

clientHeight: 只读。高度+内边距


参考链接
本文来自博客园,作者:shayloyuki,转载请注明原文链接:https://www.cnblogs.com/shayloyuki/p/16916054.html
posted on 2022-11-22 18:20 shayloyuki 阅读(332) 评论(0) 收藏 举报
浙公网安备 33010602011771号