Skip to content
Menu
Yuuk的博客
  • 首页
  • 前端技术
    • JavaScript
    • HTML & CSS
  • SEO
  • 设计
    • 素材分享
    • 设计教程
  • 随笔
Yuuk的博客

原生JS实现移动端长按效果

Posted on 2017年6月20日2017年6月22日 by yuuk

先上代码:

function longPress(options) {
	var defauts = {
		selector: 'body',
		delay: 1000,
		pressEnd: function () {}
	}
	this.opts = Object.assign({}, defauts, options);
	this.timer = null;
	this.init();
}

longPress.prototype.init = function () {
	var _this = this;
	var element = document.querySelectorAll(this.opts.selector);
	element.forEach(function(o, i, a){
		// 触摸开始
		element[i].addEventListener('touchstart', function(e){
			_this.timer = setTimeout(function(){
				_this.opts.pressEnd(e, element[i]);
				if (_this.timer) {
    				clearTimeout(_this.timer);
    			}
			}, _this.opts.delay);
		}, false);

		// 触摸结束
	    element[i].addEventListener('touchend', function(e){
			if (_this.timer) {
    			clearTimeout(_this.timer);
    		}
		}, false);
	});
}

调用方法:

new longPress({
	selector: '.banner',
	delay: 2000,
	pressEnd: function (e, ele) {
		console.log(e, ele);
	}
})

解读:

主要用到touch事件中的touchstart和touchend事件,当touchstart时候开启定时器,指定延迟时间,执行操作并清掉定时器。touchend时清除定时器。

打赏赞(1)分享

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

搜索

近期文章

  • 宝塔面板中使用docker部署nodejs应用
  • 如何将docker镜像上传到阿里云
  • React Native 报错 No bundle URL present 解决方法
  • axios 给每一个请求添加耗时统计
  • css filter属性导致fixed失效

标签

addEventListener ajax ajax跨域 chatAt css居中 DNS缓存 docker gulp ie7 json jsonp margin memcache mysql nodejs ps技巧 typescript void vpn vuejs wampserver webpack win10 XMLHttpRequest z-index 事件冒泡 事件绑定 内容发布时间 图片加载 大写 字符串 封装ajax 广告屏蔽 批量修改图层名称 水平垂直居中 注册码 特殊符号 百度 空元素 站长平台 网页快照 负边界 递减 随机数 首字母

友情链接

  • 蔡甸新闻网
©2025 Yuuk的博客 | 鄂ICP备13014750号-9