vue怎么实现按钮的长按功能
导读:本文共2543字符,通常情况下阅读需要8分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 效果图如下:实现效果图:实现思路:给需要操作的 dom 元素添加touchstart(点击开始)、touchend(点击结束)、touchmove(手指移动)事件在使用touchstart(点击开始)事件的时候设置定时器,在指定时间内如果不做其他操作就视为 长按事件,执行 长按事件 的同时需要设定当前不是 单击事件,以防止touchend(点击结束)执行的时候同... ...
目录
(为您整理了一些要点),点击可以直达。效果图如下:
实现效果图:
实现思路:
给需要操作的 dom 元素添加touchstart(点击开始)、touchend(点击结束)、touchmove(手指移动)事件
在使用touchstart(点击开始)事件的时候设置定时器,在指定时间内如果不做其他操作就视为 长按事件,执行 长按事件 的同时需要设定当前不是 单击事件,以防止touchend(点击结束)执行的时候同时出现 长按事件 和 单击事件
在 touchend(点击结束)里面清除定时器,并判断是不是 单击事件
在 touchmove(手指移动)里面清除定时器,并设定当前不是 单击事件
代码
HTML
<div@touchstart="gotouchstart"@touchmove="gotouchmove"@touchend="gotouchend"class="div">按钮</div>
JS
exportdefault{data(){return{}},methods:{//手指按下事件gotouchstart(){window.isClick=trueclearTimeout(this.timeOut)this.timeOut=setTimeout(function(){console.log('在这里执行长按事件')window.isClick=false},500)},//手释放,如果在500毫秒内就释放,则取消长按事件,此时可以执行onclick应该执行的事件gotouchend(){if(window.isClick){console.log('在这里执行点击事件')}//如果手指有移动,则取消所有事件,此时说明用户只是要移动而不是长按gotouchmove(){console.log('手指移动了')window.isClick=false}//项目销毁前清除定时器beforeDestroy(){clearTimeout(this.timeOut)}}
style(去除长按出现的文字复制影响)
-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;
补充:下面看下Vue使用自定义指令实现按钮长按提示功能,超简单!
项目场景
点击按钮实现长按,用户需要按下按钮几秒钟,然后触发相应的事件
实现思路
首先,需要创建一个计时器,在2 秒后开始执行函数,用户按下按钮时触发
mousedown
事件,开始计时;当鼠标移开按钮时开始调用
mouseout
事件第一种情况,当
mouseup
事件 2 秒内被触发了,需要清除计时器,相当于进行了普通的点击事件第二种情况,当计时器没有在 2 秒内清除,那么这就可以判定为一次长按,可以执行长按的逻辑了。
如果在移动端使用,使用的就是
touchstart
,touchend
事件了 实现效果
实现代码
<template><div> <divclass="btn-copy"><el-buttonv-press="handleClickLong">长按</el-button></div></div></template><script>importpressfrom'../../directive/test/press'exportdefault{directives:{press},data(){return{}},methods:{handleClickLong(){alert('实现了长按哦!!!')},}}</script><stylelang="scss"></style>
press.js文件如下:
constpress={bind:function(el,binding,vNode){console.log(el,binding,vNode)//el就是domif(typeofbinding.value!=='function'){throw'callbackmustbeafunction'}//定义变量letpressTimer=null//创建计时器(2秒后执行函数)letstart=(e)=>{if(e.type==='click'&&e.button!==0){return}if(pressTimer===null){pressTimer=setTimeout(()=>{handler()},2000)}}//取消计时器letcancel=(e)=>{console.log(e)if(pressTimer!==null){clearTimeout(pressTimer)pressTimer=null}}//运行函数consthandler=(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)},//当传进来的值更新的时候触发componentUpdated(el,{value}){el.$value=value},//指令与元素解绑的时候,移除事件绑定unbind(el){el.removeEventListener('click',el.handler)},}exportdefaultpress
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
vue怎么实现按钮的长按功能的详细内容,希望对您有所帮助,信息来源于网络。