在小编做开发的时候经常会有这样的需求,需要在页面上加上一个悬浮图标,那么今天我们就来讲讲有关于:“简单可拖拽移动的悬浮图标怎么实现?”这个问题的实现方法吧!

案例代码展示:

<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 相关的设置和计算。

那么以上就是有关于:“简单可拖拽移动的悬浮图标怎么实现?”这个问题小编总结的解决方法和相关内容分享,对于其他有关于html5这方面的相关内容我们都可以在W3Cschool中进行学习和了解!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。