H5 ページでシェイクを実現 (WeChat + APP に埋め込み)

要件では、ページでボタンをクリックして携帯電話を振るか、宝くじをトリガーする必要があります。

ページは WeChat ミニ プログラム + APP に表示されます。

インターネットでいくつか方法を見つけましたが、WeChat SDK には H5 ページを呼び出すシェイクメソッドが用意されていないため、次の方法をとりました。

h5 コードは、実行環境が APP であるか非 APP であるかを決定します。

1.アプリ内 

安全のため、APP が提供するシェイク メソッドを H5 に呼び出します (APP 側の開発者とネゴシエーションする必要があります)。H5 はメソッドを直接呼び出します。シェイクがトリガーされた後、シェイク メソッドを閉じる必要があります。シェイク メソッドは抽選後に抽選されますが、携帯電話を振ると引き続きトリガーされます。

2. アプリ内ではない

shade.js を使用したコードは次のようになります。

/*
 * Author: Alex Gibson
 * https://github.com/alexgibson/shake.js
 * License: MIT license
 */

(function(global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(function() {
            return factory(global, global.document);
        });
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(global, global.document);
    } else {
        global.Shake = factory(global, global.document);
    }
} (typeof window !== 'undefined' ? window : this, function (window, document) {

    'use strict';
    function Shake(options) {
        //feature detect
        this.hasDeviceMotion = 'ondevicemotion' in window;

        this.options = {
            threshold: 15, //默认摇动阈值
            timeout: 1000  //默认两次事件间隔时间
        };

        if (typeof options === 'object') {
            for (var i in options) {
                if (options.hasOwnProperty(i)) {
                    this.options[i] = options[i];
                }
            }
        }

        //使用date防止重复调用
        this.lastTime = new Date();

        //accelerometer values
        this.lastX = null;
        this.lastY = null;
        this.lastZ = null;

        //创建自定义事件
        if (typeof document.CustomEvent === 'function') {
            this.event = new document.CustomEvent('shake', {
                bubbles: true,
                cancelable: true
            });
        } else if (typeof document.createEvent === 'function') {
            this.event = document.createEvent('Event');
            this.event.initEvent('shake', true, true);
        } else {
            return false;
        }
    }

    // toast提示
    function showToast(str){
        $('.toast-box').html(str)
        $('.toast-box').show()
        var tempTimeOut = setTimeout(function(){
            $('.toast-box').html('')
            $('.toast-box').hide()
            clearTimeout(tempTimeOut)
        },5000)
    }

    //重置时间计时器
    Shake.prototype.reset = function () {
        this.lastTime = new Date();
        this.lastX = null;
        this.lastY = null;
        this.lastZ = null;
    };

    //开始监听 devicemotion
    Shake.prototype.start = function () {
        this.reset();
        var ua = navigator.userAgent.toLowerCase();
        console.log('~~~~this.hasDeviceMotion~~~~~~~',this.hasDeviceMotion)
        if (this.hasDeviceMotion) {
            if (ua.indexOf("like mac os x") > 0) {
                // 正则判断手机系统版本
                var reg = /os [\d._]*/gi ;
                var verinfo = ua.match(reg) ;
                var version = (verinfo+"").replace(/[^0-9|_.]/ig,"").replace(/_/ig,".");
                var arr=version.split(".");
                console.log('获取手机系统版本',version+'~~~~~~~'+arr[0]+"."+arr[1]+"."+arr[2]) //获取手机系统版本
                console.log('比较1111:',arr[0]>12,arr[1]>2,arr[0]>13||(arr[0]>12&&arr[1]>2))
                if (arr[0]>13||(arr[0]>12&&arr[1]>2)) {  //对13.3以后的版本处理,包括13.3
                    DeviceMotionEvent.requestPermission().then(permissionState => {
                        if (permissionState === 'granted') { //已授权
                            window.addEventListener('devicemotion', this, false);//摇一摇
                        } else if(permissionState === 'denied'){// 打开的链接不是https开头
                            showToast('当前IOS系统拒绝访问动作与方向,请"点击摇一摇按钮"参与活动')
                            // console.log("当前IOS系统拒绝访问动作与方向。请退出微信,重新进入活动页面获取权限。")
                        }
                    }).catch((err)=>{
                        showToast('当前IOS系统拒绝访问动作与方向,请"点击摇一摇按钮"参与活动')
                        // showToast('苹果设备申请摇动权限')
                        // ios13granted();
                        	// layer.open({
							// 	content: '<div style="height: 50px; text-align: center; padding-top: 20px">苹果设备申请摇动权限</div>',
							// 	btn: '允许',
							// 	// style: 'padding: 50px 30px;',
							// 	shadeClose: false,
							// 	yes: function(index){
							// 		ios13granted();
							// 		layer.close(index);
							// 	}
							// })
                    });
                }else{  //13.3以前的版本
                    console.log('ios13.3以前的版本')
                    window.addEventListener('devicemotion', this, false);
                }
            } else {
                window.addEventListener('devicemotion', this, false);
            }
        }
    };
    
    function ios13granted() {
        if (typeof DeviceMotionEvent.requestPermission === 'function') {
            DeviceMotionEvent.requestPermission().then(permissionState => {
                if (permissionState === 'granted') { //已授权
                    window.addEventListener('devicemotion', this, false);//摇一摇
                    // var myShakeEvent = new Shake({
                    //     threshold: 12
                    // });
                    // myShakeEvent.start();
                    // window.addEventListener('shake', function () {
                    //     start();
                    // }, false); //摇一摇
                } else if(permissionState === 'denied'){// 打开的链接不是https开头
                    showToast('当前IOS系统拒绝访问动作与方向,请"点击摇一摇按钮"参与活动')
                    console.log("当前IOS系统拒绝访问动作与方向。请退出微信,重新进入活动页面获取权限。")
                }
            }).catch((error) => {
                showToast('当前IOS系统拒绝访问动作与方向,请"点击摇一摇按钮"参与活动')
                console.log("请求设备方向或动作访问需要用户手势来提示")
            })
        } else {
            // 处理常规的非iOS 13+设备
            console.log("处理常规的非iOS 13+设备")
        }
    }
    //停止监听 devicemotion
    Shake.prototype.stop = function () {
        if (this.hasDeviceMotion) {
            window.removeEventListener('devicemotion', this, false);
        }
        this.reset();
    };

    //计算是否触发摇动
    Shake.prototype.devicemotion = function (e) {
        var current = e.accelerationIncludingGravity;
        var currentTime;
        var timeDifference;
        var deltaX = 0;
        var deltaY = 0;
        var deltaZ = 0;
 
        if ((this.lastX === null) && (this.lastY === null) && (this.lastZ === null)) {
            this.lastX = current.x;
            this.lastY = current.y;
            this.lastZ = current.z;
            return;
        }
 
        deltaX = Math.abs(this.lastX - current.x);
        deltaY = Math.abs(this.lastY - current.y);
        deltaZ = Math.abs(this.lastZ - current.z);
 
        if (((deltaX > this.options.threshold) && (deltaY > this.options.threshold)) || ((deltaX > this.options.threshold) && (deltaZ > this.options.threshold)) || ((deltaY > this.options.threshold) && (deltaZ > this.options.threshold))) {
            //calculate time in milliseconds since last shake registered
            currentTime = new Date();
            timeDifference = currentTime.getTime() - this.lastTime.getTime();
 
            if (timeDifference > this.options.timeout) {
                window.dispatchEvent(this.event);
                this.lastTime = new Date();
            }
        }
 
        this.lastX = current.x;
        this.lastY = current.y;
        this.lastZ = current.z;

    };

    //事件处理
    Shake.prototype.handleEvent = function (e) {
        if (typeof (this[e.type]) === 'function') {
            return this[e.type](e);
        }
    };
 
    return Shake;
}));

h5ページに導入されました

<script type="text/javascript" src="shake.js"></script>
 //创建实例
    var myShakeEvent = new Shake({
        threshold: 12 // 摇动阈值
    });
    // 监听设备动作
    myShakeEvent.start();

    //添加一个监听事件
    window.addEventListener('shake', function () {
        // start();
        console.log('摇一摇')
    }, false);

知らせ:

1. このメソッドは、ローカル共同デバッグ中にはトリガーされません。トリガーするには、h5 ページへのリンクが https://... で始まる必要があり (これは特別な落とし穴です)、WeChat はポリシーを調整し、リンクh5 ページへは SSL 暗号化を使用する必要があります。

2. シェイクは iOS 13.3 より前のバージョンでトリガーできます。それ以降のバージョンには互換性があり、ユーザーがアクションや指示を承認できるようにするには、ユーザーが手動でクリックできるポップアップ ボックスが必要です。(https プロトコルが必要です)

本当にトリガーしない場合は、デザイナーにドットバイドットスタイルを追加するように依頼してください。携帯電話を振っても本当にトリガーしない場合は、タップツードットを使用してトリガーします。

3.シェイク効果音について

呼び出し元の APP によってスローされたメソッドの場合、独自の効果音が発生する場合があります (APP 開発者がメソッドを定義する方法によって異なります)。

呼び出し元の APP によってスローされたメソッドではない場合は、次の方法でトリガーできます。

効果音: https://download.csdn.net/download/tt18473481961/87512465

<audio preload="" id="sing"><source src="images/sing.mp3" type="audio/mp3"></audio>

#sing {
  display: none;
}

var sing=document.getElementById("sing");

sing.play();

4. 一部の iOS 端末に関して、play() メソッドをシェイクしても音が出ません。

touchstart イベントをバインドします (最初にクリックされた要素に関連付けることができます。1 回だけ使用したら削除するのが最善です。理論的には touchend にバインドすることもできますが、有効にするにはクリックする必要があります。touchend はスライド後に機能しません) . .) を呼び出してから.load()、他のメソッドで呼び出して、.paly()サウンドをスムーズに再生します。

var sing=document.getElementById("sing");
$(".start").on("touchstart",function(){ // 为了解决iOS手机不点击摇一摇按钮直接调play()不发出声音
	console.log('touchstart-播放音频',document.getElementById("sing"))
	sing.load()
	sing.pause()
})
// 在其他方法中嗲用音频播放
sing.play(); // 播放声音

おすすめ

転載: blog.csdn.net/tt18473481961/article/details/129255696