使用JAVAScript技术在WEB网页实现摇一摇的应用

实现效果如下:

 代码如下:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>摇一摇</title>

</head>

<body onload="init()">

<p>用力摇一摇你手机</p>

<audio style="display:hiden;0px; height:0px;" id="musicBox" preload="metadata" controls src="http://other.web.rh01.sycdn.kuwo.cn/resource/n3/21/19/3413654131.mp3">

</audio>

</body>

<script>

init();

var SHAKE_THRESHOLD = 3000;//定义一个摇动的值

var last_update = 0;//定义一个变量保存上次更新的时间

var x = y = z = last_x = last_y = last_z = 0;//定义xyz记录三个轴的数据以及上一次出发的时间

function init() {

if (window.DeviceMotionEvent) {

window.addEventListener('devicemotion', deviceMotionHandler, false);

} else {

alert('not support mobile event');

}

}

function deviceMotionHandler(eventData) {

var meda01=document.getElementById('musicBox');

var acceleration = eventData.accelerationIncludingGravity;//含重力加速度

var curTime = new Date().getTime();//获取当前时间

if ((curTime - last_update) > 100) {//curTime - last_update 是固定时间段

var diffTime = curTime - last_update;

last_update = curTime;

//alert('last_update='+last_update)

x = acceleration.x;

//alert('x='+x)

y = acceleration.y;

//alert('y='+y)

z = acceleration.z;

//alert('z='+z)

var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

//alert('speed='+speed)  abs是取绝对值

if (speed > SHAKE_THRESHOLD) {

alert("摇动了+中大奖了,就是不知道有没有声音");

media.setAttribute("src", "http://other.web.rh01.sycdn.kuwo.cn/resource/n3/21/19/3413654131.mp3");

//setAttribute  锁定元素。此方法不能通过document对象调用,只能通过元素节点对象调用他

//例如,你可以把他与getElementByTagName()方法结合起来,去查询每个<p>元素的title属性

//var txt=document.getElementsByTagName('p')

//for(var i=0;i<text.length;i++){

//alert(txt[i].getAttribute('title'))

//}

//

//

//

//

media.load();

media.play();

meda01.play();

}

last_x = x;

last_y = y;

last_z = z;

}

}

</script>

</html>

原文地址:https://www.cnblogs.com/mutudou/p/11858574.html