html5手机摇一摇

var SHAKE_THRESHOLD = 3000;
            var last_update = 0;
            var x = y = z = last_x = last_y = last_z = 0;
            var num=0;
            var media;

            function init() {
                last_update = new Date().getTime();
                media = document.getElementById("musicBox");
                if (window.DeviceMotionEvent) {
                    window.addEventListener('devicemotion', deviceMotionHandler, false);
                } else {

                    alert("不支持手机事件!");
                }
            }


            function _animate(){
                
                var up=document.getElementById("up");
                var down=document.getElementById("down");
                var offset=up.offsetHeight/2;
                up.style.webkitTransform="translateY("+(-offset)+"px)";
                down.style.webkitTransform="translateY("+(offset)+"px)";
                
                setTimeout(function(){
                    up.style.webkitTransform="";
                    down.style.webkitTransform="";
                },500)
            }

            function deviceMotionHandler(eventData) {
                
                //accelerationIncludingGravity(含重力的加速度)和acceleration(加速度),后者排除了重力的影响。
                var acceleration = eventData.accelerationIncludingGravity; 

                var curTime = new Date().getTime();
                if ((curTime - last_update) > 100) {
                    var diffTime = curTime - last_update;
                    last_update = curTime;
                    x = acceleration.x;
                    y = acceleration.y;
                    z = acceleration.z;
                    var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
                    if (speed > SHAKE_THRESHOLD) {
                        if (!media.src) {
                            media.src = "weixin_yaoyiyao.mp3";
                        }
                        media.play();
                        _animate();
                        num++;
                        document.getElementById("num").innerHTML=num;
                    }
                    last_x = x;
                    last_y = y;
                    last_z = z;
                }

            }
        window.onload=init;

 完整例子下载

posted @ 2014-06-14 10:53  冰vs焰  阅读(193)  评论(0编辑  收藏  举报