I am using phonegap to build android apps.
我正在使用phonegap来构建Android应用程序。
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?
我想检测用户的触摸事件,以便弹出警报。但是,如何从javascript调用ontouch事件?
Thanks!
谢谢!
1 个解决方案
#1
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
.
下面是一个显示touchstart和touchend的示例。它演示了两种不同的附加触摸事件的方法:元素属性或JavaScript的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.
由于它正在侦听触摸事件,因此事件不会在桌面浏览器(支持鼠标事件)上触发。要测试该页面,您可以打开它或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>
#1
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
.
下面是一个显示touchstart和touchend的示例。它演示了两种不同的附加触摸事件的方法:元素属性或JavaScript的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.
由于它正在侦听触摸事件,因此事件不会在桌面浏览器(支持鼠标事件)上触发。要测试该页面,您可以打开它或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>