簡體   English   中英

如何使用 android 和 iphone 的 javascript 檢測長觸摸壓力?

[英]How to detect a long touch pressure with javascript for android and iphone?

如何使用 android 和 iphone 的 javascript 檢測長觸摸壓力? 本機 javascript 或 jquery ...

我想要的東西聽起來像:

<input type='button' onLongTouch='myFunc();' />

使用 Touch End 檢測長觸摸的問題在於,如果您希望事件在一段時間后觸發,它將無法工作。 最好在觸摸開始時使用計時器並在觸摸結束時清除事件計時器。 可以使用以下模式:

var onlongtouch; 
var timer;
var touchduration = 500; //length of time we want the user to touch before we do something

touchstart() {
    timer = setTimeout(onlongtouch, touchduration); 
}

touchend() {

    //stops short touches from firing the event
    if (timer)
        clearTimeout(timer); // clearTimeout, not cleartimeout..
}

onlongtouch = function() { //do something };

這是 Joshua 答案的擴展版本,因為他的代碼運行良好,直到用戶不執行多點觸控(您可以用兩根手指點擊屏幕,功能將被觸發兩次,4 根手指 - 4 次)。 在一些額外的測試場景之后,我什至觸發了非常頻繁地觸摸並在每次點擊后接收執行的功能的可能性。

我添加了一個名為“lockTimer”的變量,它應該在用戶觸發“touchend”之前鎖定任何額外的 touchstarts。

 var onlongtouch; var timer; var touchduration = 800; //length of time we want the user to touch before we do something function touchstart(e) { e.preventDefault(); if (!timer) { timer = setTimeout(onlongtouch, touchduration); } } function touchend() { //stops short touches from firing the event if (timer) { clearTimeout(timer); timer = null; } } onlongtouch = function() { timer = null; document.getElementById('ping').innerText+='ping\\n'; }; document.addEventListener("DOMContentLoaded", function(event) { window.addEventListener("touchstart", touchstart, false); window.addEventListener("touchend", touchend, false); });
 <div id="ping"></div>

我在我的 Android 應用程序中這樣做了:

  1. 注冊事件監聽器:

     var touchStartTimeStamp = 0; var touchEndTimeStamp = 0; window.addEventListener('touchstart', onTouchStart,false); window.addEventListener('touchend', onTouchEnd,false);
  2. 新增功能:

     var timer; function onTouchStart(e) { touchStartTimeStamp = e.timeStamp; } function onTouchEnd(e) { touchEndTimeStamp = e.timeStamp; console.log(touchEndTimeStamp - touchStartTimeStamp);// in miliseconds }
  3. 檢查時差並完成我的工作

我希望這會有所幫助。

我們可以計算觸摸開始和觸摸結束的時間差。 如果計算出的時間差超過觸摸持續時間,那么我們使用函數名稱 taphold。

var touchduration = 300; 
var timerInterval;

function timer(interval) {

    interval--;

    if (interval >= 0) {
        timerInterval = setTimeout(function() {
                            timer(interval);
                        });
    } else {
        taphold();
    }

}

function touchstart() {
    timer(touchduration);
}

function touchend() {
    clearTimeout(timerInterval);
}

function taphold(){
    alert("taphold");
}


document.getElementById("xyz").addEventListener('touchstart',touchstart);
document.getElementById("xyz").addEventListener('touchend',touchend);

此處發布的解決方案忽略了用戶需要觸摸屏幕才能啟動滾動的事實。 如果用戶不嘗試滾動,我們只想要長按行為。

function onLongPress(element, callback) {
  let timer;

  element.addEventListener('touchstart', () => { 
    timer = setTimeout(() => {
      timer = null;
      callback();
    }, 500);
  });

  function cancel() {
    clearTimeout(timer);
  }

  element.addEventListener('touchend', cancel);
  element.addEventListener('touchmove', cancel);
}

然后:

onLongPress(element, () => {
  console.log('Long pressed', element);
});

對於跨平台開發人員:

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)
});

這個基於@Joshua 的更好的解決方案,有時需要直接在事件內部調用代碼(某些 Web API 需要用戶操作來觸發某些內容),對於這種情況,您可以使用以下修改:

var longtouch;
var timer;
//length of time we want the user to touch before we do something
var touchduration = 500;

function touchstart() {
    longtouch = false;

    timer = setTimeout(function() {
       longtouch = true;
       timer = null
    }, touchduration);
}

function touchend() {
    if (timer) {
        clearTimeout(timer);
        timer = null;
    }
    if (longtouch) {
        // your long acction inside event
        longtouch = false;
    }
}

在 setTimeout 中將標志設置為 true 並在 touchend 內部檢查它是否已設置。

就在這里: http//m14i.wordpress.com/2009/10/25/javascript-touch-and-gesture-events-iphone-and-android/

使用touchstarttouchend可以在一段時間內檢測長時間的觸摸

這適用於我的用例,即想要在觸摸屏幕時執行某些功能。

let triggerInterval = 200; // in milliseconds
let timerId;

function touchstart(e) {
  // e.preventDefault();
  timerId = setInterval(yourFunction, triggerInterval);
}

function touchend(e) {
  clearInterval(timerId);
}

function yourFunction() {
  //   perform your logic
}

document.addEventListener("touchstart", touchstart);
document.addEventListener("touchend", touchend);

注意:- triggerInterval 中的較小值將更快地執行yourFunction()

完成程序后,您可以刪除相應的事件偵聽器:

document.removeEventListener("touchstart", touchstart);
document.removeEventListener("touchend", touchend);

基於@djanowski 的解決方案來處理觸摸滾動。 這也應該防止長按上下文菜單和選擇。

 function onLongPress(element, callback) { var timeoutId; element.addEventListener('touchstart', function(e) { timeoutId = setTimeout(function() { timeoutId = null; e.stopPropagation(); callback(e.target); }, 500); }); element.addEventListener('contextmenu', function(e) { e.preventDefault(); }); element.addEventListener('touchend', function () { if (timeoutId) clearTimeout(timeoutId); }); element.addEventListener('touchmove', function () { if (timeoutId) clearTimeout(timeoutId); }); } onLongPress(document.getElementById('kitty1'), function(element) { alert('Meow from ' + element.outerHTML ); }); onLongPress(document.getElementById('kitty2'), function(element) { alert('Meow from ' + element.outerHTML ); });
 img { max-width: 100%; -webkit-user-select: none; /* Safari */ -ms-user-select: none; /* IE 10 and IE 11 */ user-select: none; /* Standard syntax */ }
 <p>Long press on kitty! Kitty should meow on 500ms long press but not scroll</p> <img id="kitty1" src="http://placekitten.com/300/400" /> <img id="kitty2" src="http://placekitten.com/300/300" />

適用於所有瀏覽器的長按事件

(function (a) {
        function n(b) { a.each("touchstart touchmove touchend touchcancel".split(/ /), function (d, e) { b.addEventListener(e, function () { a(b).trigger(e) }, false) }); return a(b) } function j(b) { function d() { a(e).data(h, true); b.type = f; jQuery.event.handle.apply(e, o) } if (!a(this).data(g)) { var e = this, o = arguments; a(this).data(h, false).data(g, setTimeout(d, a(this).data(i) || a.longclick.duration)) } } function k() { a(this).data(g, clearTimeout(a(this).data(g)) || null) } function l(b) {
            if (a(this).data(h)) return b.stopImmediatePropagation() ||
            false
        } var p = a.fn.click; a.fn.click = function (b, d) { if (!d) return p.apply(this, arguments); return a(this).data(i, b || null).bind(f, d) }; a.fn.longclick = function () { var b = [].splice.call(arguments, 0), d = b.pop(); b = b.pop(); var e = a(this).data(i, b || null); return d ? e.click(b, d) : e.trigger(f) }; a.longclick = { duration: 500 }; a.event.special.longclick = {
            setup: function () {
                /iphone|ipad|ipod/i.test(navigator.userAgent) ? n(this).bind(q, j).bind([r, s, t].join(" "), k).bind(m, l).css({ WebkitUserSelect: "none" }) : a(this).bind(u, j).bind([v,
                w, x, y].join(" "), k).bind(m, l)
            }, teardown: function () { a(this).unbind(c) }
        }; var f = "longclick", c = "." + f, u = "mousedown" + c, m = "click" + c, v = "mousemove" + c, w = "mouseup" + c, x = "mouseout" + c, y = "contextmenu" + c, q = "touchstart" + c, r = "touchend" + c, s = "touchmove" + c, t = "touchcancel" + c, i = "duration" + c, g = "timer" + c, h = "fired" + c
    })(jQuery);

以時間間隔綁定longclick事件

 $('element').longclick(250, longClickHandler);

下面的功能在觸摸設備上的 Long Tap 上觸發

function longClickHandler() {
    alter('Long tap Fired');
}

暫無
暫無

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

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