H5实现悬浮图标

2,448 阅读1分钟

前言

今天遇到了一个小小的问题,要求在H5页面中实现一个悬浮按钮,按钮固定在一侧可以上下滑动。

代码

话不多说,直接上代码。
<template>
        <div class="suspension-icon-weiliao"  id='suspension'
            :style="{'width': '1rem','height': '1rem','right': right+'rem','bottom': bottom+'rem'}"    
            ref="div"    
            @touchstart.stop="(e) => {dragStart(e)}" 
            @touchend.stop="(e) => {dragEnd(e)}"     
            @touchmove.prevent="(e) => {dragProgress(e)}" 
            @click.stop="callWeiLiao()"   
            >    
        </div>
</template>
methods: {
        dragStart(e) { 
            this.$refs.div.style.transition = 'none';
        },
        dragEnd(e) {        
            this.$refs.div.style.transition = 'all 0s';        
            this.right = 0.1;
        },      
        dragProgress(e) {      
            if (e.targetTouches.length === 1) {          
                let touch = e.targetTouches[0];   

                this.right = 0.1;              
                this.bottom = (document.documentElement.clientHeight - touch.clientY) / 50;
                if (touch.clientY <= 130) {
                    this.bottom = (document.documentElement.clientHeight - document.getElementsByClassName('suspension-icon-weiliao').offsetHeight) / 50;
                }

                if (touch.clientY >= (document.documentElement.clientHeight - 130)) {
                    this.bottom = 1.3;
                }
            }      
        },
    },

这是一个被封装好的组件,调用时只需该改组件加上position: fixed;即可。

目前还存在的问题

无法适配不同的机型,我们会发现在不同机子上,悬浮按钮距离顶部的距离是大小不一的。

待解决

上面会出现的问题,touchstart.prevent会阻止click事件的发生。而touchmove去掉prevent后会导致微聊悬浮窗和页面一起滑动。修改后如下

    <template>
        <div class="suspension-icon-weiliao"  id='suspension'
            :style="{'width': '1rem','height': '1rem','right': right+'rem','bottom': bottom+'rem'}"    
            ref="div"    
            @touchstart.stop="(e) => {dragStart(e)}" 
            @touchend.stop="(e) => {dragEnd(e)}"     
            @touchmove.prevent="(e) => {dragProgress(e)}" 
            @click.stop="callWeiLiao()"   
            >    
        </div>
</template>