HTML笔记 ·

js模仿微信摇一摇功能

微信推出后,他的摇一摇功能非常的火爆,没事来微信摇一摇加加好友,我们可不可以借鉴一下微信的摇一摇功能,让手机访问网页的时候,只要手机摇一摇,网页背景就会自动随时换一个网页背景。
具体想要用摇一摇的功能思路已经确认的了,现在就是来实现代码的了。我们现在是用HTML5实现摇一摇的功能。JS代码如下:

<script type="text/javascript">  
var color = new Array('#fff', '#ff0', '#f00', '#000', '#00f', '#0ff');  
if(window.DeviceMotionEvent) {  
    var speed = 25;  
    var x = y = z = lastX = lastY = lastZ = 0;  
    window.addEventListener('devicemotion', function(){  
        var acceleration =event.accelerationIncludingGravity;  
        x = acceleration.x;  
        y = acceleration.y;  
        if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed) {  
            document.body.style.backgroundColor = color[Math.round(Math.random()*10)%6];  
        }  
        lastX = x;  
        lastY = y;  
    }, false);  
}  
</script>

有兴趣的童鞋可以更多的扩展一下,通过js来实现更多摇一摇的功能。祝大家好运。。。

上面的代码是在html5下实现的。下面我再分享另外一段js实现的方法,大家可以对比一下:

用javascript实现手机摇一摇

if(navigator.userAgent.indexOf('iPhone')>-1)
{
    var SHAKE_THRESHOLD =2000;
}
else
{
    if(navigator.userAgent.indexOf('QQ')>-1)
    {
        var SHAKE_THRESHOLD =1000;
    }
    else
    {
        var SHAKE_THRESHOLD =4000;
    }
 
}
 
根据手机反应的不同SHAKE_THRESHOLD值可以设置为不同的值
 
var last_update = 0;
var x, y, z, last_x=0, last_y=0, last_z=0;
 
function deviceMotionHandler(eventData) {
 
    var acceleration =eventData.accelerationIncludingGravity;
    var curTime = new Date().getTime();
 
    if ((curTime - last_update)> 100) {
        var diffTime = parseInt(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) {
            alert('摇一摇');
            
        }
        last_x = x;
        last_y = y;
        last_z = z;
    }
}
 
 
if (window.DeviceMotionEvent) {
            window.addEventListener('devicemotion',deviceMotionHandler, false);
    }

 

参与评论