zoukankan      html  css  js  c++  java
  • 移动端H5长按事件 vue自定义指令

     1 import Vue from 'vue'
     2 Vue.directive('longpress', function (el, binding){
     3   var timer = null;
     4   var start = function (e) {
     5       // 如果是点击事件,不启动计时器,直接返回
     6       if (e.type === 'click'){
     7           return
     8       }
     9       if (timer == null){
    10           // 创建定时器 ( 2s之后执行长按功能函数 )
    11           timer = setTimeout(function () {
    12               //执行长按功能函数
    13               binding.value()
    14           },2000)
    15       }
    16   }
    17   var cancel = function () {
    18       if (timer !== null){
    19           clearTimeout(timer)
    20           timer = null
    21       }
    22   }
    23 
    24   // 添加事件监听器
    25   el.addEventListener("mousedown", start);
    26   el.addEventListener("touchstart", start);
    27 
    28   // 取消计时器
    29   el.addEventListener("click", cancel);
    30   el.addEventListener("mouseout", cancel);
    31   el.addEventListener("touchend", cancel);
    32   el.addEventListener("touchcancel", cancel);
    33 })

    1.在src目录下 新建文件夹utils文件夹,然后新建derective.js,复制上方代码,粘贴到derective.js;
    2.在main.js中引入 该自定义指令js
    3.在html中可以这样使用即可 

    <h2 v-longpress="handleLongClick">测试长按事件是否生效</h2>

    总结:支持移动端跟pc端

    
    
  • 相关阅读:
    webstorm 取消拖动代码
    可读流
    页面上怎么使用svg
    从element-ui按需引入去探索
    vue组件库用markdown生成文档
    create-react-app中的babel配置探索
    svg 使用中的疑惑点
    express中是如何处理IP的?
    koa中是如何封装获取客户端IP的?
    博客园文章添加目录
  • 原文地址:https://www.cnblogs.com/chenhuichao/p/12060970.html
Copyright © 2011-2022 走看看