vue怎么实现按钮的长按功能(vue,开发技术)

时间:2024-04-27 17:45:51 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

效果图如下:

实现效果图:

vue怎么实现按钮的长按功能

实现思路:

给需要操作的 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 秒内清除,那么这就可以判定为一次长按,可以执行长按的逻辑了。

  • 如果在移动端使用,使用的就是 touchstarttouchend 事件了 实现效果

vue怎么实现按钮的长按功能

实现代码

<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怎么实现按钮的长按功能的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:如何进行c++11中std::move函数的使用下一篇:

14 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18