App下載

簡單可拖拽移動的懸浮圖標怎么實現(xiàn)?示例代碼詳解!

執(zhí)手不憶殤 2021-08-18 11:28:09 瀏覽數(shù) (2920)
反饋

在小編做開發(fā)的時候經(jīng)常會有這樣的需求,需要在頁面上加上一個懸浮圖標,那么今天我們就來講講有關(guān)于:“簡單可拖拽移動的懸浮圖標怎么實現(xiàn)?”這個問題的實現(xiàn)方法吧!

案例代碼展示:

<div class="ys-float-btn" 
    :style="{'width': itemWidth+'px','height': itemHeight+'px','left': left+'px','top': top+'px'}"    
    ref="div"    
    @touchstart.prevent="(e) => {dragStart(e)}"     
    @touchend.prevent="(e) => {dragEnd(e)}"     
    @touchmove.prevent="(e) => {dragProgress(e)}"    
    >    
    <img src="./../assets/fc-icon.png" />
</div>
// 代碼直接在 vue 項目里,可自行改為js/jquery 寫法
data () {
    return {
        gapWidth: 10,
        itemWidth: 20, // 圖標的寬度
        itemHeight: 30 // 圖標的高度
    }
},
created() {      
    this.clientWidth = document.documentElement.clientWidth;     
    this.clientHeight = document.documentElement.clientHeight;      
    this.left = this.clientWidth - this.itemWidth - this.gapWidth;      
    this.top = this.clientHeight*0.8;   }
 
methods: {    
    dragStart(e) {        
        this.$refs.div.style.transition = 'none';
    },
    dragEnd(e) {        
        this.$refs.div.style.transition = 'all 0.3s';        
        if (this.left > this.clientWidth/2) {          
            this.left = this.clientWidth - this.itemWidth - this.gapWidth;
        } else {          
            this.left = this.gapWidth;        
        }      
    },      
    dragProgress(e) {        
        if (e.targetTouches.length === 1) {          
            let touch = event.targetTouches[0];          
            this.left = touch.clientX - this.itemWidth/2;              
            this.top = touch.clientY - this.itemHeight/2;        
        }      
    }
} 

以上代碼既可以上下也可以左右移動,如果只想讓可上下移動,就去掉 left 相關(guān)的設(shè)置和計算。

那么以上就是有關(guān)于:“簡單可拖拽移動的懸浮圖標怎么實現(xiàn)?”這個問題小編總結(jié)的解決方法和相關(guān)內(nèi)容分享,對于其他有關(guān)于html5這方面的相關(guān)內(nèi)容我們都可以在W3Cschool中進行學習和了解!


0 人點贊