javascript 如何使用vue js滚动结束页面

bihw5rsg  于 2022-11-27  发布在  Java
关注(0)|答案(4)|浏览(144)

如何滚动到页面底部?

scroll(){
    let container = this.$el.querySelector('#scrollingChat')
    container.scrollTop = container.scrollHeight
}

我正在这样做,并且总是调用我的api答案,但它不会转到页面底部

rpppsulh

rpppsulh1#

window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);

这将立即滚动到任何页面的底部。

piwo6bdm

piwo6bdm2#

如果您在页面中创建锚,如下所示:

<div id="top"></div>

您可以用途:

let elmnt = document.getElementById('top');
elmnt.scrollIntoView(false);

本页说明不同的对齐参数对scrollIntoView的作用:

true-滚动到元素顶部
false-滚动到元素底部

默认为true
https://www.w3schools.com/jsref/met_element_scrollintoview.asp

hgb9j2n6

hgb9j2n63#

window.scrollTo(0,document.body.scrollHeight);

也可以使用平滑滚动:https://github.com/alamcordeiro/vue-smooth-scroll

zf9nrax1

zf9nrax14#

您可以参考Mozilla Docs
VueJS在代码方面最安全的用法是使用nextTick()ref属性,尤其是在事件后触发执行时(例如:如果你使用一些VueJS框架,+的效果最好。
滚动可以与smooth行为一起应用,以获得更好的UX。

特定div的示例

<template><div ref="myScrollTarget">...</div></template>
<script>
...
methods: {
  scrollToBottom() {
    const targetRef = this.$refs.myScrollTarget;
    this.$nextTick(() => {
      targetRef.scrollTo(
        {
          top: targetRef.scrollHeight,
          left: 0,
          behavior: "smooth"
        }
      );
    });
  }
}
...
</script>

整页示例(窗口)

<template><div>...</div></template>
<script>
...
methods: {
  scrollToBottom() {
    this.$nextTick(() => {
      window.scrollTo(
        {
          top: document.body.scrollHeight,
          left: 0,
          behavior: "smooth"
        }
      );
    });
  }
}
...
</script>

相关问题