vue模拟jquery点击滚动事件

vue模拟jquery点击滚动事件

初始代码如下,滚动速度有点欠缺

1. html

<template>
    <div id="scroll">
       <h4>vue模拟jquery的scroll滚动</h4>
       <dl class="nav">
         <dd v-for="(item,key) in this.navs" :key="key" @click="scroll" :to="item.to">
           <a :href="item.route">
              {{item.content}}
           </a>
         </dd>
       </dl>
       <div id="content">
         <section id="home">
           <h4>首页</h4>
           <p class="pages"></p>
         </section>
         <section id="about_us">
           <h4>关于我们</h4>
           <p class="pages"></p>
         </section>
         <section id="foot">
           <h4>页脚</h4>
           <p class="pages"></p>
         </section>
       </div>
    </div>
</template>

2. js,主要是scroll方法

methods:{
          scroll(e){
            let that = e.currentTarget
            let id = that.getAttribute('to')
            let end_pos = document.querySelector(id).offsetTop
            let start_pos = document.body.scrollTop || document.documentElement.scrollTop
            let speed = 30,
                time=15
            console.log(end_pos,start_pos)
            let current = start_pos
            if(start_pos >= end_pos){
              up()
            }else{
              down()
            }

            function pos(pos){
              document.body.scrollTop = pos   //ie,Chrome
              document.documentElement.scrollTop = pos   //Firefox
            }

            function up(){
               current -= speed
               if(current >= end_pos){
                 pos(current)
                 setTimeout(()=>{
                   up()
                 },time)
               }else{
                 pos(end_pos)
               }
            }
            function down() {
              current += speed
              if(current <= end_pos){
                pos(current)
                setTimeout(()=>{
                  down()
                },time)
              }else{
                pos(end_pos)
              }
            }
  }

3. data数据

data(){
          return {
            navs:[
              {
                content:'首页',
                route:'javascript:;',
                to:'#home'
              },
              {
                content:'关于我们',
                route:'javascript:;',
                to:'#about_us'
              },
              {
                content:'页脚',
                route:'javascript:;',
                to:"#foot"
              }
            ]
          }
        }

主要还是scroll方法

展开阅读全文

没有更多推荐了,返回首页