美文网首页
vue项目苹果手机浏览器解决橡皮筋效果和默认滚屏效果

vue项目苹果手机浏览器解决橡皮筋效果和默认滚屏效果

作者: ChasenGao | 来源:发表于2019-11-22 10:08 被阅读0次

现在很多手机厂商都对主流手机的内置浏览器做了橡皮筋效果,所谓橡皮筋效果,就是页面出了可以按照自身内容滚动外,body元素也可以在window内上下弹动。大概动图如下:

IPhone 8 13.x系统效果如下: 顶部区域的橡皮筋效果导致网页整体可下拉。


image.png

之前在华为手机上(忘记哪个型号)也见过类似橡皮筋效果。
之前是做一个全屏手触Canvas签名的功能,有的手机没有橡皮筋效果,可以正常全屏签名。但是做了这种处理的手机,全屏触摸式屏幕就会跟着手势滑动,导致无法触摸签名。

最近在Vue项目上也遇见了这个问题,所以索性解决一下。

既然用电脑浏览器没事儿,手机浏览器有事,那肯定是touch事件的问题,于是我在代码里做了一下处理。

<script>
    /* eslint-disable */
    function fn(e) {
        e.preventDefault()
    }
    export default {
        name: "customer_signature",
        mounted(){
            document.body.addEventListener('touchstart',fn,{passive:false})
        },
        beforeDestroy(){
            document.body.removeEventListener('touchstart',fn)
        }
    }
</script>

进入页面之后,添加对touchstart事件的处理,离开页面时取消处理,目的是不影响其它页面。

为了保险一点,我还对根元素的样式做了fixed定位。

<template>
    <div class="container">
        <signature ref="pad" class="u-signature"></signature>
    </div>
</template>
<style scoped lang="less">
    .container {
        overflow: hidden;
    }
    .u-signature {
        touch-action: none;
        width: 100vw!important;
        height: 100vh!important;
        position: fixed;
        top: 0;
        left: 0;
        overflow: hidden;
    }
</style>

试了一下,还真是可以了。但是我发现页面上的按钮全都无法点击。(上面代码未提供按钮部分,请往下看)

因为我的画布是全屏的,所以我把按钮做了position: absolute; 让他能够显示在页面上,但是因为我一进页面就处理了body的touchstart时间,没有最近父级position元素的时候,position:absolute又是根据body元素进行定位的,所以我按钮点击事件也被一起处理掉了。
原因是点击和触摸时间触发的规则是:
1、手指点按,未离开屏幕,触发touchstart事件。
2、手指点按,未拖动,并且快速离开屏幕(也就是点击操作),触发 touchstart -> click事件。
3、手指点按,拖动,并离开屏幕。 触发 touchstart -> touchmove -> touchend事件。

也就是说如果我在touchstart事件做了处理,那我无论如何都无法触发点击事件。
那我就在touchmove事件处理不得了。
修改后,完全可用。
下面贴出完整代码:

请不要直接复制,复制了未必能直接使用,参考即可:


<template>
    <div class="container">
        <signature ref="pad" class="u-signature"></signature>
        <button  @click="asdasd" style="margin-top: 60vh;position: absolute">dsajdaskdjsa</button>
    </div>
</template>

<script>
    /* eslint-disable */
    function fn(e) {
        e.preventDefault()
    }
    export default {
        name: "customer_signature",
        mounted(){
            document.body.addEventListener('touchmove',fn,{passive:false})
        },
        beforeDestroy(){
            document.body.removeEventListener('touchmove',fn)
        },
        methods:{
            asdasd(){
                alert(1)
            }
        }

    }
</script>

<style scoped lang="less">
    .container {
        overflow: hidden;
    }
    .u-signature {
        touch-action: none;
        width: 100vw!important;
        height: 100vh!important;
        position: fixed;
        top: 0;
        left: 0;
        overflow: hidden;
    }
</style>

相关文章

网友评论

      本文标题:vue项目苹果手机浏览器解决橡皮筋效果和默认滚屏效果

      本文链接:https://www.haomeiwen.com/subject/ygugictx.html