问题描述
我使用的PhoneGap构建Android应用程序。
I am using phonegap to build android apps.
我想检测来自用户的触摸事件,所以我可以弹出一个警告。但是,如何从JavaScript调用的ontouch事件?
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?
谢谢!
推荐答案
下面是一个例子,显示了 touchstart
和 touchend
。它展示了两种不同的方式连接触摸事件:元素的属性或JavaScript的的addEventListener
Below is an example that shows touchstart
and touchend
. It demonstrates two different ways to attach touch events: element attributes or JavaScript's addEventListener
.
由于它监听的触摸事件,该事件将不会在桌面浏览器触发(支持鼠标事件)。要测试页面,你可以打开一个Android或iOS的模拟器。
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>
这篇关于如何检测用户触摸与PhoneGap的使用JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!