H5网页监听长按事件

来源:IT星空
访问量:345
发布日期:2023-07-09

以下是在网上复制的一段代码,亲测可用,根据自己实际的网页内容做简单修改即可使用:

 

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="format-detection" content="telephone=no">
		<title>长按事件测试</title>
		<script src="static/js/jquey1.12.4.js"></script>
		<style type="text/css">

		</style>
	<body>

		<div style="width:100%;">
			<div id="touchArea" style="width:90%; height:200px; background-color:#CCC;font-size:100px">长按我</div>
		</div>

	</body>

	<script>
		// // H5页面监听长按事件

		var timeOutEvent = 0;
		$(function() {
			$("#touchArea").on({
				touchstart: function(e) {
					timeOutEvent = setTimeout("longPress()", 500);
					e.preventDefault();
				},
				touchmove: function() {
					clearTimeout(timeOutEvent);
					timeOutEvent = 0;
				},
				touchend: function() {
					clearTimeout(timeOutEvent);
					if (timeOutEvent != 0) {
						console.log("这是点击,不是长按");
					}
					return false;
				}
			})
		});

		function longPress() {
			timeOutEvent = 0;
			console.log("长按事件触发");
		}
	</script>


</html>