移动端事件

移动端事件

触屏事件

移动端事件要比PC端要简单的多,
移动端主要就有ontouchstart ontouchend ontouchmove ontouchcancel 几种下面来一一介绍

  • ontouchstart
    相当于PC端的onmousedown

    box.ontouchstart=function(){
      box.style.left="200px"; }
    

用法和onmousedown 用法相同

  • ontouchend
    相当于PC端的onmouseup

    box.ontouchend=function(){
      box.style.left="100px";}
    

用法和onmouseup相似

  • ontouchmove
    相当于PC端的onmousemove

    redDiv.ontouchstart=function(){
      document.ontouchmove=function(){
          var evObj=window.event || ev;
          redDiv.style.left=evObj.changedTouches[0].pageX+'px';
          redDiv.style.top=evObj.changedTouches[0].pageY+'px';
          
            return false;
          }}
      redDiv.ontouchend  = function(){
      document.ontouchmove = null;}
    

上面那个例子是让redDiv跟随手指滑动而运动

  • ontouchcancel
    取消触摸的时候触发。比如来电话、信息等,系统中止触摸事件的时候会触发,每个手机触发方式不一样。

每个触屏事件都包含事件对象。事件对象常用的有三个属性

  • touches 屏幕上所有的手指列表
  • targetTouches 元素内的所有手指列表
  • changedTouches 改变了状态的手指列表

两个设备事件 加速器和陀螺仪

  • if (window.DeviceMotionEvent)判断手机是否支持

  • 动态的重力加速度
    accelerationIncludingGravity包括了重力加速度的X,y ,z 的三个方向
    下面一个例子获取当前的重力加速度,X轴Y轴Z轴

      window.ondevicemotion=function(){
              var evObj=window.event ||ev;
              var x=evObj.accelerationIncludingGravity.x;
              var y=evObj.accelerationIncludingGravity.y;
              var z=evObj.accelerationIncludingGravity.z;
              blueDiv.innerHTML="x:"+x+"
    "+"y"+y+"
    "+"z:"+z; } }else{ redDiv.innerHTML="换个手机吧" }

下面是螺旋仪的例子

window.ondeviceorientation=function(ev){
        var evObj=window.event ||ev;
        var alpha=parseInt(evObj.alpha);
        var beta=parseInt(evObj.beta);
        var gamma=parseInt(evObj.gamma);
        blueDiv.innerHTML="alpha:"+alpha+"
"+"beta:"+beta+"
"+"gamma:"+gamma; }

你可能感兴趣的:(移动端事件)