1 <!DOCTYPE HTML> 2 <HTMLLang= "en"> 3 <Head> 4 <MetaCharSet= "Utf-8" /> 5 <Metaname= "Viewport"content= "Width=device-width, initial-scale=1.0" /> 6 <title>Shake a shake function</title> 7 </Head> 8 <Bodyonload= "init ()"> 9 <P>Shake your phone hard</P> Ten <AudioID= "MusicBox"Controls SRC=""/> One </Body> A </HTML> - <Scripttype= "Text/javascript"> - //Javascript the varShake_threshold= the; - varlast_update= 0; - varx=y=Z=last_x=last_y=last_z= 0; - functioninit () { + if(window. Devicemotionevent) { - Window.addeventlistener ('devicemotion', Devicemotionhandler,false); + } Else { A Alert ('Not support Mobile event'); at } - } - functionDevicemotionhandler (eventData) { - varAcceleration=eventdata.accelerationincludinggravity; - varCurtime= NewDate (). GetTime (); - if((Curtime-last_update)> -) { in varDifftime=Curtime-last_update; - last_update=Curtime; to x=acceleration.x; + y=ACCELERATION.Y; - Z=acceleration.z; the var Speed=Math.Abs (x+y+Z-last_x-last_y-last_z)/Difftime* 10000; * $ if( speed>shake_threshold) { Panax Notoginseng Alert ("Shake it, play it"); - varMedia=document.getElementById ("MusicBox");//Get audio Control the Media.setattribute ("src","Http://1.html5weby1y.sinaapp.com/2.mp3"); + media.load ();//Loading Audio A Media.play ();//Play Audio the } + last_x=x; - last_y=y; $ last_z=Z; $ } - } - </Script>
HTML5 Web shake a shake to switch songs