【问题标题】:scrollintoView not taking component to the top of the pagescrollintoView 不将组件带到页面顶部
【发布时间】:2021-11-01 22:18:29
【问题描述】:

下面是 home.vue 组件,它有 service 和 legal 两个其他组件。如果 id 存在,在mounted() 中我有吗?然后滚动查看法律部分。我在这里面临的问题是它确实滚动了一点,但没有将法律部分滚动到页面顶部。附上图片。请帮我找出哪里出错了

home.vue

<template>
  <div>
    <Service id="service"></Service>
    <br />
    <hr>
    <Legal id="legal"></Legal>
  </div>
</template>

<script>
import Service from 'views/home/service.vue';
import Legal from 'views/legal.vue';

export default {
  components: {
    Service,
    Legal,
  },
  props: ['id'],
  mounted() {
    // this.id == 'legal'
    if (this.id) {
      this.$nextTick(()=> window.document.getElementById('legal').scrollIntoView());
    }
  }
};
</script>

【问题讨论】:

  • 我不确定整个页面是什么样的,但只是为了澄清一下,它只是将其滚动到 Legal 组件的顶部吗?
  • @nbixler 是的,没错,它只是将其滚动到法律组件的顶部,而不是将法律组件带到页面顶部。
  • 您可能已经考虑过这一点,但是您可以在 Home.vue 模板中交换 Service 和 Legal 组件吗?这会让你得到你想要的效果吗?或者,您可以包含您当前的 css 吗?您可能希望将一个类附加到 Legal 以使其具有绝对定位(或粘贴到页面顶部等)。
  • @nbixler 我无法切换这两个组件。
  • @nbixler 你能解释一下替代部分吗?也许我可以试试。

标签: javascript vue.js vuetify.js


【解决方案1】:

尝试使用querySelector

mounted(){
    if(this.id){
      const el = this.$el.querySelector("#service");
      if (el) {
        el.scrollIntoView();
      }
    }
  }

codepen - https://codepen.io/Pratik__007/pen/bGrYYZP

【讨论】:

  • const el = this.$el.querySelector("#legal") 返回未定义
猜你喜欢
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多