DBMNG数据库管理与应用

才能是来自独创性。独创性是思维、观察、理解和判断的一种独特的方式。
当前位置:首页 > 经验分享 > HTML5

H5移动端原生长按事件

1、需求:封装移动端长按事件

2、分析:JavaScript原生并不存在长按事件,所以我们需要通过touchstart 、touchmove 、touchend来模拟并封装一个长按事件

3、上代码*(函数名为:longpress,参数为:需长按元素的id、长按之后的逻辑函数 func)*

// 函数名longpress,参数为: 需长按元素的id、长按之后的逻辑函数func

function longpress(id, func) {


var timeOutEvent;

document.querySelector('#' + id).addEventListener('touchstart', function (e) {

// 开启定时器前先清除定时器,防止重复触发

clearTimeout(timeOutEvent);

// 开启延时定时器

timeOutEvent = setTimeout(function () {

// 调用长按之后的逻辑函数func

func();

}, 300);  // 长按时间为300ms,可以自己设置

});

document.querySelector('#' + id).addEventListener('touchmove', function (e) {

// 长按过程中,手指是不能移动的,若移动则清除定时器,中断长按逻辑

clearTimeout(timeOutEvent);

/* e.preventDefault() --> 若阻止默认事件,则在长按元素上滑动时,页面是不滚动的,按需求设置吧 */

});

document.querySelector('#' + id).addEventListener('touchend', function (e) {

// 若手指离开屏幕时,时间小于我们设置的长按时间,则为点击事件,清除定时器,结束长按逻辑

clearTimeout(timeOutEvent);

});

}


本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号