一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

html5实现可拖拽移动的悬浮图标代码示例

时间:2021-03-25 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下html5实现可拖拽移动的悬浮图标代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

h5 上经常会有这样的需求:

需要在页面上加上一个悬浮图标,大致是如下图的最终实现

但是往往按照设计稿是不会遮住主体区域的,但是实际上有时候偏偏会遮挡主体区域,但是为了更好的点击量,又不得不悬浮在页面上...

如果能让图标可拖拽移动,这样在遮住主体区域之后,用户可自由移动,这种方案及可以兼顾了。

实现的效果如下:

(和微信的浮窗效果类似,左右位置靠边显示,上下位置随意放)

代码如下

// 代码直接在 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;        
        }      
    }
} 

热门栏目