簡體   English   中英

在 JavaScript 中長按?

[英]Long Press in JavaScript?

是否可以在 JavaScript(或 jQuery)中實現“長按”? 如何?

替代文字
(來源: androinica.com

HTML

<a href="" title="">Long press</a>

JavaScript

$("a").mouseup(function(){
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  return false; 
});

沒有“jQuery”魔法,只有 JavaScript 計時器。

var pressTimer;

$("a").mouseup(function(){
  clearTimeout(pressTimer);
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() { ... Your Code ...},1000);
  return false; 
});

根據 Maycow Moura 的回答,我寫了這個。 它還確保用戶沒有執行右鍵單擊,這會觸發長按並在移動設備上工作。 演示

var node = document.getElementsByTagName("p")[0];
var longpress = false;
var presstimer = null;
var longtarget = null;

var cancel = function(e) {
    if (presstimer !== null) {
        clearTimeout(presstimer);
        presstimer = null;
    }

    this.classList.remove("longpress");
};

var click = function(e) {
    if (presstimer !== null) {
        clearTimeout(presstimer);
        presstimer = null;
    }

    this.classList.remove("longpress");

    if (longpress) {
        return false;
    }

    alert("press");
};

var start = function(e) {
    console.log(e);

    if (e.type === "click" && e.button !== 0) {
        return;
    }

    longpress = false;

    this.classList.add("longpress");

    if (presstimer === null) {
        presstimer = setTimeout(function() {
            alert("long click");
            longpress = true;
        }, 1000);
    }

    return false;
};

node.addEventListener("mousedown", start);
node.addEventListener("touchstart", start);
node.addEventListener("click", click);
node.addEventListener("mouseout", cancel);
node.addEventListener("touchend", cancel);
node.addEventListener("touchleave", cancel);
node.addEventListener("touchcancel", cancel);

您還應該使用 CSS 動畫包含一些指標:

p {
    background: red;
    padding: 100px;
}

.longpress {
    -webkit-animation: 1s longpress;
            animation: 1s longpress;
}

@-webkit-keyframes longpress {
    0%, 20% { background: red; }
    100% { background: yellow; }
}

@keyframes longpress {
    0%, 20% { background: red; }
    100% { background: yellow; }
}

您可以使用 jQuery 移動 API 的taphold事件。

jQuery("a").on("taphold", function( event ) { ... } )

我創建了long-press-event (0.5k pure JS)來解決這個問題,它向 DOM 添加了一個long-press事件。

long-press任何元素:

// the event bubbles, so you can listen at the root level
document.addEventListener('long-press', function(e) {
  console.log(e.target);
});

long-press特定元素:

// get the element
var el = document.getElementById('idOfElement');

// add a long-press event listener
el.addEventListener('long-press', function(e) {

    // stop the event from bubbling up
    e.preventDefault()

    console.log(e.target);
});

適用於 IE9+、Chrome、Firefox、Safari 和混合移動應用程序(iOS/Android 上的 Cordova 和 Ionic)

演示

雖然它看起來很簡單,可以通過超時和幾個鼠標事件處理程序自行實現,但當您考慮單擊-拖動-釋放等情況時,它會變得有點復雜,在同一元素上同時支持按下和長按,並使用 iPad 等觸控設備。 我最終使用了longclick jQuery 插件( Github ),它為我處理這些事情。 如果你只需要支持手機等觸屏設備,你也可以試試jQuery Mobile taphold event

jQuery 插件。 只需輸入$(expression).longClick(function() { <your code here> }); . 第二個參數是保持持續時間; 默認超時為 500 毫秒。

(function($) {
    $.fn.longClick = function(callback, timeout) {
        var timer;
        timeout = timeout || 500;
        $(this).mousedown(function() {
            timer = setTimeout(function() { callback(); }, timeout);
            return false;
        });
        $(document).mouseup(function() {
            clearTimeout(timer);
            return false;
        });
    };

})(jQuery);

對於現代移動瀏覽器:

document.addEventListener('contextmenu', callback);

https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu

$(document).ready(function () {
    var longpress = false;

    $("button").on('click', function () {
        (longpress) ? alert("Long Press") : alert("Short Press");
    });

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

    $("button").on('mouseup', function () {
        endTime = new Date().getTime();
        longpress = (endTime - startTime < 500) ? false : true;
    });
});

演示

對於跨平台開發人員(注意到目前為止給出的所有答案都不適用於 iOS)

Mouseup/down 在android上似乎工作正常 - 但不是所有設備,即(三星 tab4)。 iOS上根本不起作用。

進一步研究似乎這是由於具有選擇的元素和本地放大率中斷了聽者。

如果用戶將圖像保留 500 毫秒,則此事件偵聽器允許在引導模式中打開縮略圖圖像。

它使用響應式圖像類,因此顯示圖像的較大版本。 這段代碼已經在 (iPad/Tab4/TabA/Galaxy4) 上進行了全面測試:

var pressTimer;  
$(".thumbnail").on('touchend', function (e) {
   clearTimeout(pressTimer);
}).on('touchstart', function (e) {
   var target = $(e.currentTarget);
   var imagePath = target.find('img').attr('src');
   var title = target.find('.myCaption:visible').first().text();
   $('#dds-modal-title').text(title);
   $('#dds-modal-img').attr('src', imagePath);
   // Set timeout
   pressTimer = window.setTimeout(function () {
      $('#dds-modal').modal('show');
   }, 500)
});

Diodeus 的回答很棒,但它阻止您添加 onClick 函數,如果您放置 onclick,它永遠不會運行保持函數。 而Razzak的回答幾乎是完美的,但它只在mouseup上運行保持功能,並且通常即使用戶保持保持該功能也會運行。

所以,我加入了兩者,並做到了這一點:

$(element).on('click', function () {
    if(longpress) { // if detect hold, stop onclick function
        return false;
    };
});

$(element).on('mousedown', function () {
    longpress = false; //longpress is false initially
    pressTimer = window.setTimeout(function(){
    // your code here

    longpress = true; //if run hold function, longpress is true
    },1000)
});

$(element).on('mouseup', function () {
    clearTimeout(pressTimer); //clear time on mouseup
});

您可以在鼠標按下時設置該元素的超時並在鼠標抬起時清除它:

$("a").mousedown(function() {
    // set timeout for this element
    var timeout = window.setTimeout(function() { /* … */ }, 1234);
    $(this).mouseup(function() {
        // clear timeout for this element
        window.clearTimeout(timeout);
        // reset mouse up event handler
        $(this).unbind("mouseup");
        return false;
    });
    return false;
});

有了這個,每個元素都有自己的超時。

您可以使用 jquery-mobile 的 taphold。 包括 jquery-mobile.js 和以下代碼將正常工作

$(document).on("pagecreate","#pagename",function(){
  $("p").on("taphold",function(){
   $(this).hide(); //your code
  });    
});

最優雅和干凈的是一個 jQuery 插件: https : //github.com/untill/jquery.longclick/ ,也可以作為 Packacke 使用: https ://www.npmjs.com/package/jquery.longclick。

簡而言之,您可以像這樣使用它:

$( 'button').mayTriggerLongClicks().on( 'longClick', function() { your code here } );

這個插件的優點是,與這里的其他一些答案相比,點擊事件仍然是可能的。 另請注意,在鼠標懸停之前,會發生長按,就像在設備上長按一樣。 所以,這是一個特點。

我需要長按鍵盤事件的東西,所以我寫了這個。

var longpressKeys = [13];
var longpressTimeout = 1500;
var longpressActive = false;
var longpressFunc = null;

document.addEventListener('keydown', function(e) {
    if (longpressFunc == null && longpressKeys.indexOf(e.keyCode) > -1) {
        longpressFunc = setTimeout(function() {
            console.log('longpress triggered');
            longpressActive = true;
        }, longpressTimeout);

    // any key not defined as a longpress
    } else if (longpressKeys.indexOf(e.keyCode) == -1) {
        console.log('shortpress triggered');
    }
});

document.addEventListener('keyup', function(e) {
    clearTimeout(longpressFunc);
    longpressFunc = null;

    // longpress key triggered as a shortpress
    if (!longpressActive && longpressKeys.indexOf(e.keyCode) > -1) {
        console.log('shortpress triggered');
    }
    longpressActive = false;
});

這對我有用:

const a = document.querySelector('a');

a.oncontextmenu = function() {
   console.log('south north');
};

https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/oncontextmenu

在 vanila JS 中,如果需要在點擊釋放后檢測長點擊:

    document.addEventListener("mousedown", longClickHandler, true);
    document.addEventListener("mouseup", longClickHandler, true);

    let startClick = 0;
    function longClickHandler(e){   
      if(e.type == "mousedown"){
        startClick = e.timeStamp;
      }
      else if(e.type == "mouseup" && startClick > 0){
        if(e.timeStamp - startClick > 500){  // 0.5 secound
          console.log("Long click !!!");
        }
      }
    }

如果需要在單擊時檢查長按,可能需要使用計時器。 但對於大多數情況,發布后點擊就足夠了。

對我來說,它適用於該代碼(使用 jQuery):

var int       = null,
    fired     = false;

var longclickFilm = function($t) {
        $body.css('background', 'red');
    },
    clickFilm = function($t) {
        $t  = $t.clone(false, false);
        var $to = $('footer > div:first');
        $to.find('.empty').remove();
        $t.appendTo($to);
    },
    touchStartFilm = function(event) {
        event.preventDefault();
        fired     = false;
        int       = setTimeout(function($t) {
            longclickFilm($t);
            fired = true;
        }, 2000, $(this)); // 2 sec for long click ?
        return false;
    },
    touchEndFilm = function(event) {
        event.preventDefault();
        clearTimeout(int);
        if (fired) return false;
        else  clickFilm($(this));
        return false;
    };

$('ul#thelist .thumbBox')
    .live('mousedown touchstart', touchStartFilm)
    .live('mouseup touchend touchcancel', touchEndFilm);

可以通過查看時間來識別 Click 或 Long Press [jQuery]

function AddButtonEventListener() {
try {
    var mousedowntime;
    var presstime;
    $("button[id$='" + buttonID + "']").mousedown(function() {
        var d = new Date();
        mousedowntime = d.getTime();
    });
    $("button[id$='" + buttonID + "']").mouseup(function() {
        var d = new Date();
        presstime = d.getTime() - mousedowntime;
        if (presstime > 999/*You can decide the time*/) {
            //Do_Action_Long_Press_Event();
        }
        else {
            //Do_Action_Click_Event();
        }
    });
}
catch (err) {
    alert(err.message);
}
} 

像這樣?

target.addEeventListener("touchstart", function(){
   // your code ...
}, false);    

您可以使用jquery觸摸事件。 見這里

  let holdBtn = $('#holdBtn')
  let holdDuration = 1000
  let holdTimer

  holdBtn.on('touchend', function () {
    // finish hold
  });
  holdBtn.on('touchstart', function () {
    // start hold
    holdTimer = setTimeout(function() {
      //action after certain time of hold
    }, holdDuration );
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM