html - 单击按钮并转到 Vue.js 中的页面部分

标签 html vue.js button

我想实现一个自动滚动到位于同一页面上的特定 div id="contactMe" 的按钮。我正在使用 vue.js。

我用原生js尝试了下面的方法。

    <input
        onClick="document.getElementById('contactMe').scrollIntoView();"
        type="submit"
        class="cta-button bg-yellow mt-8 flex justify-center"
        :value="$frontmatter.contactFormButton"
      />

但是,我在控制台中收到以下错误。

Uncaught TypeError: Cannot read property 'scrollIntoView' of null at HTMLInputElement.onclick ((index):1)

vue框架中正确的命令是什么?

最佳答案

不要使用 input[type="submit"] 因为它只应提交 form。一个简单的 button 可以处理正确的 Vue 事件:

new Vue({
  el: '#app',
  data: {
    buttonText: 'Lorem'
  },
  methods: {
    scroll() {
      const element = document.getElementById('contact-me');
      element.scrollIntoView({ behavior: 'smooth' });
    }
  }
})
body {
  background: #20262E;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

#contact-me {
  margin-top: 2000px;
  margin-bottom: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="scroll">{{ buttonText }}</button>
  
  <div id="contact-me">
    contact me box
  </div>
</div>

关于html - 单击按钮并转到 Vue.js 中的页面部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59531829/

相关文章:

javascript - 按 id 过滤对象并找到最高分

vue.js - 如何在 Vuetify 中将内容对齐到 v-card 组件的中心?

html - data-add-back-button 不显示后退按钮

javascript - 使用 Jquery 禁用特定列的 click fot td

javascript - 生成具有特定类的文本字段

html - 如何在html中为 anchor 标签执行对齐

javascript - 引入多个代码参数

javascript - 对计算的 Vue 属性使用条件

html - 单击按钮时,我的本地 C 驱动器正在打开

android - 在android中转动横向时以编程方式添加的按钮消失