赞
踩
js里面没有长按事件 通过 touchstart 和 touchend 来实现
Vue.directive('longpress', (el, binding) => { // if (typeof binding.value !== 'function') { // throw Error(binding.value + '不是函数') // } // Make sure expression provided is a function if (typeof binding.value !== 'function') { // Fetch name of component const compName = vNode.context.name; // pass warning to console let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be`; if (compName) { warn += `Found in component '${compName}' `; } console.warn(warn); } let pressTimer = null; // 开始按下 const start = (e) => { // 如果是点击事件,不启动计时器,直接返回 if (e.type === 'click' && e.button !== '0') { return; } if (pressTimer == null) { // 创建定时器 (2s之后执行长按功能韩函数) pressTimer = setTimeout(() => { binding.value(); // 执行长按功能函数 }, 1000); } }; // 取消按下 const cancel = (e) => { if (pressTimer != null) { clearTimeout(pressTimer); pressTimer = null; } }; // 添加事件监听器 el.addEventListener('mousedown', start); el.addEventListener('touchstart', start); // 取消计时器 el.addEventListener('click', cancel); el.addEventListener('mouseout', cancel); el.addEventListener('touchend', cancel); el.addEventListener('touchcancel', cancel); });
html 使用
<div id="touchId" v-longpress="touchStar" :class="tipShow == true ? 'tips' : ''" :data-content="tip">长按触发</div
// 长按
touchStar(e) {
this.tip = '我是长按触发的';
if (this.tipsTimer != null) return;
this.tipShow = true;
this.tipsTimer = setTimeout(() => {
this.tipShow = false;
this.tipsTimer = null;
}, 3000);
},
css样式
[v-cloak] { display: none } #touchId { position: relative; font-size: 16px; //下面代码避免长按 选择文字 -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .tips:before { content: ''; position: absolute; top: 10px; left: 6px; width: 0; height: 0; border: 6px solid transparent; border-bottom-color: rgba(0, 0, 0, .7); } .tips:after { content: attr(data-content); position: absolute; top: 22px; left: 0; white-space: nowrap; background-color: rgba(0, 0, 0, .7); color: white; padding: 4px 10px; border-radius: 3px; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。