JS事件

来源:互联网 发布:加工中心铣圆编程 编辑:程序博客网 时间:2024/06/05 02:45

实现原理:

1.微信摇一摇事件需要有硬件支撑,必须要求手机中有陀螺仪

2.在JS中给window添加ondevectionmotion事件。该事件在手机晃动,即手机中的陀螺仪发生旋转,该事件会触发

3.触发ondevectionmotion事件,会产生一个事件对象,通过该对象中的键值(accelerationIncludingGravity)来获得该重力加速器对象

4.重力加速器对象中含有陀螺仪的坐标,通过重力加速器对象.x - .y - .z 获取陀螺仪当前的坐标

<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><title>微信摇一摇</title></head><body><!--请摇一摇--></body><script type="text/javascript">function randomNum(m,n){return Math.floor(Math.random(n - m + 1) + m);}//cover设置背景尺寸//将背景图按所在标签的宽高,缩放document.body.style.backgroundSize = "cover";//设置body的背景图document.body.style.backgroundImage = "url(img/bg.jpg)" ;//事件设备:触发该事件需要硬件支持//摇一摇功能://1.手机中的陀螺仪加速两次 加速器的差值当达到某个值时,则认为是手机晃动事件//2.设置手机晃动事件前,获取加速器的值//3.添加手机晃动事件;//获取手机晃动前加速器的值,创建一个对象获取var currentValue = {x : 0,y : 0,z : 0};//获取手机晃动之后加速器的值,创建一个对象获取var lastValue = {x : 0,y : 0,z : 0}//设置晃动的最小的距离,只有达到该距离时,才执行摇一摇事件var minValue = 20;//当手机触发摇一摇事件时,我们得到此时的位置信息,存储到一个p标签上//理论上讲:陀螺仪事件中的加速器是无法静止的;var p1 = document.createElement("p");//第一种方式:var img1 = document.createElement("img");img1.style.width = "375px";img1.style.height = "560px";//手机晃动事件window.ondevicemotion = function(e){//获取对象var event1 = event || e;//获取加速器对象,为了获取陀螺仪上的坐标信息var acceleration = event1.accelerationIncludingGravity;//记录当前加速器的值currentValue.x = acceleration.x;currentValue.y = acceleration.y;currentValue.z = acceleration.z;//判断微信摇一摇事件(手机是否晃动)if (Math.abs(currentValue.x - lastValue.x) >= minValue || Math.abs(currentValue.y - lastValue.y) > minValue || Math.abs(currentValue.z - lastValue.z) > minValue) {//说明摇一摇事件触发//实现微信摇一摇,可以将摇一摇中的图片,作为body的背景图//随机一张图片的下标(1 - 5)var ranN = randomNum(1,6);//创一个定时器var timer = setInterval(function(){ranN ++ if (ranN == 6) {ranN = 1;}//为当前的body设置背景图//document.body.style.backgroundImage = "url(img/"+ranN+".jpg)";//为当前img设置路径img1.src = "img/"+ranN+".jpg";},200);//设置一个延时器,延时一段时间后消除延时器setTimeout(function(){clearInterval(timer);},1000);}//记录最后的值(保存上一次晃动事件中的加速器的值)lastValue.x = currentValue.x;lastValue.y = currentValue.y;lastValue.z = currentValue.z;}document.body.appendChild(img1);</script></html>

注意:该代码中没有上传图片,如需要运行需要自己在代码的同级目录创建一个img文件夹,里面放上从1到6的后缀为.jpg的图片

原创粉丝点击