2

我希望有一个更优雅的解决方案来解决这个问题。基本上,我有一个 HTML / Javascript 应用程序,它将在触摸屏信息亭上运行。如果有人通过拖动手指滚动按钮列表,我试图阻止默认点击行为。起初,当它检测到滑动事件时,我试图阻止默认。但后来我突然想到,这并不是真正的滑动事件,而是长时间的鼠标按下。所以我写了以下代码:

var downClick;
var startTime;

$(".TPGSW-wrapper").on('mousedown', function () {

    downClick = new Date();
    startTime = downClick.getTime();

});

$(".TPGSW-wrapper").on('mouseup', function () {

    var upClick = new Date();
    var endTime = upClick.getTime();

    if (endTime - startTime < 250) {
        return false;
    } else if (endTime - startTime >= 300) {
        // This is the action that I can't seem to get to work. 
        // I would like it to stop the click event. I also tried mouseup
        this.on('click', function () { preventDefault; });
    }              

});

这正确地测量了鼠标按下的时间,但是我似乎无法阻止点击事件的触发。有什么想法或建议吗?我正在使用 jquery,这仅用于 webkit 浏览器。提前致谢!

4

2 回答 2

2

好的,经过一些测试,我能够让它与以下代码一起工作:

var longpress = false;

$(".TPGSW-wrapper").on('click', function (e) {
    (longpress) ?  e.preventDefault() : alert("clicked");
});

var startTime, endTime;
$(".TPGSW-wrapper").on('mousedown', function () {
    startTime = new Date().getTime();
});

$(".TPGSW-wrapper").on('mouseup', function () {
    endTime = new Date().getTime();

    if (endTime - startTime < 250) {
        longpress = false;
        console.log('< 250');
    } else if (endTime - startTime >= 300) {
        longpress = true;
        console.log('>= 300');
    }

});

演示

如果鼠标按住少于 250 毫秒,点击事件将触发,如果超过 300 毫秒,它将调用e.preventDefault并停止点击事件。

于 2013-03-25T17:36:01.170 回答
1
else if (endTime - startTime >= 300) {
    $(this).one('click', function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();
    });
}

请注意如何使用“one”而不是“on”。所以它只会触发一次,而不是每次触发。

或者根据 JCOC611 的评论,您可以删除 mouseup 事件并就地使用它:

$(".TPGSW-wrapper").on('click', function (e) {
    var upClick = new Date();
    var endTime = upClick.getTime();

    if (endTime - startTime >= 300) {
        e.preventDefault();
        e.stopImmediatePropagation();
    }              
});
于 2013-03-25T17:36:42.577 回答