最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to detect user touch with phonegap using JS - Stack Overflow

programmeradmin0浏览0评论

I am using phonegap to build android apps.

I would like to detect the touch event from a user so I can pop-up an alert. However, how do I call the ontouch event from javascript?

Thanks!

I am using phonegap to build android apps.

I would like to detect the touch event from a user so I can pop-up an alert. However, how do I call the ontouch event from javascript?

Thanks!

Share Improve this question edited Mar 4, 2012 at 10:13 Waynn Lue 11.4k8 gold badges52 silver badges77 bronze badges asked Jan 28, 2011 at 8:28 DayzzaDayzza 1,5577 gold badges18 silver badges30 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 16

Below is an example that shows touchstart and touchend. It demonstrates two different ways to attach touch events: element attributes or JavaScript's addEventListener.

Since it is listening for touch events, the events will not fire on a desktop browser (which supports mouse events). To test the page, you can open it a Android or iOS simulator.

<!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>
发布评论

评论列表(0)

  1. 暂无评论