搜索

点击按钮滚动轴滑动到指定位置 - shayloyuki -


发布时间: 2022-11-24 20:49:00    浏览次数:45 次

问题

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

效果

image

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

image

    /* 添加属性按钮 */
    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.scrollHeightcontent.clientHeight 的值是一样的。

即有第二种方法container.scrollTop = content.clientHeight - container.clientHeight

怎样获取到 content ?

image

image

由于 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 包裹,否则滚动位置是在空白数据条的上方,即:

image

总结

scrollTop: 可读可写。滑动滚动条,获取元素滚动条到元素顶部的距离。


scrollHeight只读。若 container 没有添加 overflow 属性时,container 的像素高度【(content 的高度+内边距+border+外边距)+container的内边距】

image


clientHeight: 只读。高度+内边距

image


image

参考链接

  1. HTML DOM scrollTop 属性

  2. HTML DOM scrollHeight 属性

  3. HTML DOM clientHeight 属性

  4. vue中$ref和$el的区别?

  5. JavaScript之scrollTop、scrollHeight、offsetTop、offsetHeight等属性学习笔记

免责声明 点击按钮滚动轴滑动到指定位置 - shayloyuki - ,资源类别:文本, 浏览次数:45 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 08:49:00。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/shayloyuki/p/16916054.html