vue滑動內容實現橫向滑動滾動條效果


一、這個滑動可能存在一點小問題,因為這個再項目中使用率不高,所以我沒進行仔細測試。
代碼中的起名有點錯位,這里懶得改了。廢話不多少,直接上代碼。

<template>
  <div>
    <div class="grand">
        <div class="parent"
          @mousedown="handlemouse">
                隨便搜一篇滿分作文,好看滑動效果
                永恆之於我是整個生命,而瞬間之於我是每一剎那的哀傷和翻然悔悟。正是有無數個難忘或是不經意的瞬間,才完整了我的生命。

                驟冷的降雪讓我有些意外,有些驚喜。但是望着窗外愈加緊湊的雪片,我裹了裹身上單薄的外套繼續躲在教室里。
                
                忽然有同學告訴我,說我父母給我送被子來了,正往寢室里去。我高興地沖了出去,不是因為怕沒有厚被子蓋被凍,而是父母來了,
               
        </div>
    </div>
  </div>
</template>

<script>
import url from "../../common/api";
export default {
  data(){
    return {
        isDrag:false,//是否在拖拽
        isClick:false,//是否是單擊
    };
  },
  methods:{
    handlemouse(e){
        let startTime,endTime;
        let child=document.getElementsByClassName('parent')[0];
        let parent=document.getElementsByClassName('grand')[0];
        // 使用this.$refs.name獲取dom元素,可能會獲取到vue組件,他不支持獲取元素的寬高以及監聽鼠標事件
        let widthDiffer=parent.offsetWidth - child.offsetWidth;
        if(widthDiffer>0){
            //如果grand真實寬度比parent寬度長,那么就不用滑動了,直接返回
            this.isClick=true;
            return
        }
        startTime=new Date().getTime();//獲取事件開始時間
        let disx= e.clientX - child.offsetLeft;
        this.isDrag=true;//設置開始拖拽
        parent.onmousemove =(e)=>{
          if(this.isDrag){//拖拽中
              let mouseX=e.clientX; // 鼠標點擊的位置
              let x=mouseX-disx;
              // 這里判斷是開頭和結尾和大盒子對齊
              if(x>0){
                child.style.left='0px'
              }else if(x<-2300){
                child.style.left='-2300px'
              }else{
                child.style.left=x+'px'//設置parent的位置
              }
          }
        }
        parent.onmouseup=(e)=>{
          endTime=new Date().getTime();
          let timeDiffer=endTime-startTime;//獲取抬起時間
          this.isDrag=false;
          if(timeDiffer<150){
              //時間間隔小於150,那么就判斷為單擊事件,這里時間間隔可自由設置
              this.isClick=true;
          }else{
              this.isClick=false;
              //拖拽結束,如果這里parent移出了grand邊界,
              parent.onmouseout=(ev)=>{
                this.isDrag=false;
              }
          }
        }
      
    },
  },
  mounted(){
    
  }
}
</script>

<style lang="stylus" scoped>
.grand{
  height: 60px;
  width:700px;
  background #f00
  position: relative;
  overflow: hidden; 
}
.parent{
  width:3000px;
  position: absolute;
  background #00f
  white-space: nowrap;
}
</style>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM