当前位置:首页 > jquery

jquery 长按

2026-04-08 12:11:20jquery

jquery 长按

jQuery 实现长按事件的方法

在 jQuery 中实现长按(长按触摸或鼠标按住)事件可以通过结合 mousedownmouseupsetTimeout 来实现。以下是具体实现方法:

jquery 长按

基本实现

var pressTimer;

$("#target").on('mousedown touchstart', function(e) {
    // 设置定时器,延迟执行长按操作
    pressTimer = setTimeout(function() {
        // 长按事件的处理逻辑
        console.log("长按事件触发");
    }, 1000); // 设置长按时间为1000毫秒(1秒)
});

$("#target").on('mouseup touchend mouseleave', function(e) {
    // 清除定时器,防止长按事件被触发
    clearTimeout(pressTimer);
});

优化版本(支持触摸事件)

var pressTimer;
var longPressed = false;

$("#target").on('mousedown touchstart', function(e) {
    longPressed = false;
    pressTimer = setTimeout(function() {
        longPressed = true;
        // 长按事件的处理逻辑
        console.log("长按事件触发");
    }, 1000);
});

$("#target").on('mouseup touchend click', function(e) {
    clearTimeout(pressTimer);
    // 如果长按事件已触发,阻止点击事件
    if (longPressed) {
        e.preventDefault();
        e.stopPropagation();
    }
});

封装为 jQuery 插件

如果需要重复使用长按事件,可以将其封装为 jQuery 插件:

(function($) {
    $.fn.longPress = function(fn, duration) {
        var timer;
        var longPressed = false;
        duration = duration || 1000;

        this.on('mousedown touchstart', function(e) {
            longPressed = false;
            timer = setTimeout(function() {
                longPressed = true;
                fn.call(this, e);
            }, duration);
        });

        this.on('mouseup touchend click', function(e) {
            clearTimeout(timer);
            if (longPressed) {
                e.preventDefault();
                e.stopPropagation();
            }
        });

        return this;
    };
})(jQuery);

// 使用方式
$("#target").longPress(function() {
    console.log("长按事件触发");
}, 1500); // 设置长按时间为1500毫秒

注意事项

  • 在移动设备上,touchstarttouchend 事件需要与 mousedownmouseup 一起绑定以确保兼容性。
  • 长按时间可以根据需求调整,通常设置在 500 毫秒到 1500 毫秒之间。
  • 如果长按事件触发后需要阻止后续的点击事件,可以通过 preventDefaultstopPropagation 实现。

以上方法可以灵活应用于需要长按交互的场景,如长按删除、长按编辑等。

标签: jquery
分享给朋友:

相关文章

react 如何引入jquery

react 如何引入jquery

引入 jQuery 到 React 项目 在 React 项目中引入 jQuery 可以通过多种方式实现,但需要注意 React 和 jQuery 操作 DOM 的方式可能冲突,因此建议仅在必要时使用…

jquery js

jquery js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够更高…

使用jquery

使用jquery

引入jQuery库 在HTML文件中通过<script>标签引入jQuery库。可以从CDN加载,例如: <script src="https://code.jquery.com/…

jquery 选择器

jquery 选择器

jQuery 选择器基础语法 jQuery 选择器基于 CSS 选择器语法扩展,用于快速定位 DOM 元素。基本结构为 $("selector") 或 jQuery("selector"),返回一个包…

jquery时间

jquery时间

jQuery 时间处理 jQuery 本身不提供专门的时间处理函数,但可以通过 JavaScript 的 Date 对象结合 jQuery 的事件和方法来实现时间操作。以下是常见的时间处理需求及实现方…

jquery提交表单

jquery提交表单

使用 jQuery 提交表单 jQuery 提供了多种方法来提交表单,以下是常见的几种实现方式: 监听表单提交事件 通过监听表单的 submit 事件,可以阻止默认提交行为并执行自定义逻辑(如 Aj…