js双击及以上的事件处理

多次点击监听类

// 连续点击 点击次数大于1使用
class ContinuityClick {
    constructor(options = {}) {
        // 参数
        this._options = options  // 包含 clickCount  需要点击的次数 clickCount为1时必须使用todoFunc回调方法
        this.clickCount = options.clickCount || 2
        this.todoFunc = options.todoFunc || function () {}  // 点击次数>=2的回调方法
        this.singleFunc = options.singleFunc || function() {}  // 单击1次的回调方法
        this.milliseconds = options.milliseconds || 300

        this.lastTime = 0
        this.count = 0
        this.timer = null
    }
    // 返回点击次数 包含点击次数为1时的使用方式  多次以上兼容为1时的用法
    click() {
        let currentTime = new Date().getTime()
        this.count = (currentTime - this.lastTime) < this.milliseconds ? this.count + 1 : 1
        this.lastTime = new Date().getTime()
        if (this.count == this.clickCount) {
            if (typeof(this.todoFunc) == 'function') {
                this.todoFunc();
            }
        } else {
            if (typeof(this.singleFunc) == 'function') {
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    if (this.count == 1) {
                        this.singleFunc()    
                    }
                }, 250);
            }
        }
    }
}
export default ContinuityClick

使用方式

举例:vue当中
import ContinuityClick from './ContinuityClick'

template
    <button @click="clickBtn()">双击</button>

script
    export default {
        data() {
            continuityClickObj: null  
        },
        create() {
            this.continuityClickObj = new ContinuityClick({
                clickCount: 2,
                todoFunc: this.doubleClickEvent,
                singleFunc: this.dingleClicEvent
            })
        },
        methods: {
            clickBtn() {
                this.continuityClickObj.click()
            },
            // 双击两次就会触发该方法
            doubleClickEvent() {
                // todo
            },
            // 单击按钮时触发该方法
            dingleClicEvent() {
                // todo
            }
        }
    }






©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容