<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>
<style>
/*防止长按选中文字*/
.testDiv{
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
</style>
</head>
<body>
<div>
<button class="longTap" onClick="console.log('tap')" >长按</button>
<div class="testDiv" style="height:60px;background:darkolivegreen" onclick="console.log(111)">hahahhahhahahahahhahhahahha</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vconsole@3.3.4/dist/vconsole.min.js"></script>
<script>
var vConsole = new VConsole();
class LongPress{
constructor(type,el, callback) {
this.callback = callback
this.type = type
this.el = document.querySelector(el);
this.timer = null;
this.startTimeStamp = null
this.endTimeStamp = null
this.init();
}
init() {
this.el.addEventListener('touchstart',(e)=>{
this.touchstart(e)
})
this.el.addEventListener('touchend',(e)=>{
this.touchend(e)
})
}
touchstart(e) {
console.log('touchstart',e)
// 清除默认行为
//e.preventDefault();
// 开启定时器
this.timer = setTimeout(() => {
if (typeof this.callback === 'function') {
this.callback();
} else {
console.error('callback is not a function!');
}
}, 700);
//记录start时间戳
this.startTimeStamp = e.timeStamp
}
touchend(e) {
console.log('touchend',e)
this.endTimeStamp = e.timeStamp
//console.log('end',this,this.timer,this.endTimeStamp-this.startTimeStamp)
// 清除默认行为
//e.preventDefault();
// 清除定时器
clearTimeout(this.timer);
}
}
new LongPress('longtap','.longTap',function () {
console.log('long pressing....')
})
new LongPress('longtap','.testDiv',function () {
console.log(1234556)
})
/*class Person{//定义了一个名字为Person的类
constructor(name,age){//constructor是一个构造方法,用来接收参数
this.name = name;//this代表的是实例对象
this.age=age;
}
say(){//这是一个类的方法,注意千万不要加上function
return "我的名字叫" + this.name+"今年"+this.age+"岁了";
}
}
var obj=new Person("laotie",88);
console.log(obj.say());//我的名字叫laotie今年88岁了*/
</script>
</body>
</html>
js 长按
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 在移动端,可以根据touchStart与touchEnd的间隔来判断是点击,双击,还是长按; 主要的代码: let...
- 在移动H5开发中,长按保存分享图片到手机相册算是必需功能。实现原理: 下载html2canvas库的JS文件导入到...