如何使用JS检测用phonegap的用户触摸

Day*_*zza 7 javascript android touch cordova

我正在使用phonegap来构建Android应用程序.

我想检测用户的触摸事件,以便弹出警报.但是,如何从javascript调用ontouch事件?

谢谢!

mwb*_*oks 16

下面是一个显示touchstart和示例touchend.它演示了两种不同的附加触摸事件的方法:元素属性或JavaScript addEventListener.

由于它正在侦听触摸事件,因此事件不会在桌面浏览器(支持鼠标事件)上触发.要测试该页面,您可以将其打开为Android或iOS模拟器.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0;" />
    <style type="text/css">
      a {
        color:black;
        display:block;
        margin:10px 0px;
      }
    </style>

    <script type="text/javascript">
      function onload() {
        document.getElementById('touchstart').addEventListener('touchstart', hello, false);
        document.getElementById('touchend').addEventListener('touchend', bye, false);
      }

      function hello() {
        alert('hello');
      }

      function bye() {
        alert('bye');
      }
    </script>

    <title>Touch Example</title>
  </head>
  <body onload="onload();">
    <h1>Touch</h1>
    <a href="#" ontouchstart="hello();return false;">Attribute: ontouchstart</a>
    <a href="#" ontouchend="bye();return false;">Attribute: ontouchend</a>
    <a href="#" id="touchstart">addEventListener: touchstart</a>
    <a href="#" id="touchend">addEventListener: touchend</a>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)