本文环境:windows7、vue2.9.6,该方法适用于所有品牌的电脑。
vue.js实现移动端长按事件的方法:
方法一:使用@touchstart
,@touchend
start () { clearTimeout(this.loop); //再次清空定时器,防止重复注册定时器 this.loop = setTimeout(() => { console.log("长按了"); }, 1000); }, end () { clearTimeout(this.loop); //清空定时器,防止重复注册定时器 },
备注:使用的时候注意如果是图片,建议把图片设置为背景,直接使用图片,在长按时会触发浏览器对图片的保存、分享等。
方法二:
// 指令 export default { install(Vue, options = { time: 2000, }) { Vue.directive('longpress', { bind: function(el, binding, vNode) { if (typeof binding.value !== 'function') { const compName = vNode.context.name let warn = `[longpress:] provided expression '${binding.expression}' is not afunction, but has to be ` if (compName) { warn += `Found in component '${compName}' ` } console.warn(warn) } // 定义变量 let pressTimer = null // 定义函数处理程序 // 创建计时器( 1秒后执行函数 ) let start = (e) => { if (e.type === 'click' && e.button !== 0) { return } if (pressTimer === null) { pressTimer = setTimeout(() => { // 执行函数 handler() }, options.time) } } // 取消计时器 let cancel = (e) => { // 检查计时器是否有值 if (pressTimer !== null) { clearTimeout(pressTimer) pressTimer = null } } // 运行函数 const handler = (e) => { // 执行传递给指令的方法 binding.value(e) } // 添加事件监听器 el.addEventListener('mousedown', start) el.addEventListener('touchstart', start) // 取消计时器 el.addEventListener('click', cancel) el.addEventListener('mouseout', cancel) el.addEventListener('touchend', cancel) el.addEventListener('touchcancel', cancel) }, }) }, }
方法三:vue自定义手势
如果给父元素添加v-longTap
事件,点击子元素时无法触发点击事件。
以上就是vue.js怎么实现移动端长按事件的详细内容,更多请关注其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。