programing tip

JavaScript로 길게 누르시겠습니까?

itbloger 2020. 8. 3. 08:44
반응형

JavaScript로 길게 누르시겠습니까?


JavaScript (또는 jQuery)에서 "long press"를 구현할 수 있습니까? 어떻게?

대체 텍스트
(출처 : androinica.com )

HTML

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

자바 스크립트

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

JavaScript 타이머 만있는 'jQuery'마술이 없습니다.

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 mobile API의 taphold 이벤트를 사용할 수 있습니다 .

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

시간 초과 및 몇 가지 마우스 이벤트 핸들러를 사용하여 자체적으로 구현할 수있을 정도로 단순 해 보이지만 클릭-드래그-릴리즈와 같은 경우를 고려할 때 동일한 요소를 누르거나 길게 누르는 것을 고려하면 조금 더 복잡해집니다. iPad와 같은 터치 장치를 사용하여 작업합니다. longclick jQuery 플러그인 ( Github )을 사용하여 결국 그 일을 처리합니다. 휴대 전화와 같은 터치 스크린 장치 만 지원해야하는 경우 jQuery Mobile 탭 홀드 이벤트를 시도 할 수도 있습니다 .


jQuery 플러그인. 그냥 넣어 $(expression).longClick(function() { <your code here> });. 두 번째 매개 변수는 유지 기간입니다. 기본 시간 초과는 500ms입니다.

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

내가 만든 긴 프레스 이벤트 (0.5K 순수 자바 스크립트) 이 문제를 해결하기를, 그것은 추가 long-press는 DOM에 이벤트를.

A에 대한 듣기 long-press어떤 요소 :

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

A에 대한 듣기 long-pressA의 특정의 요소 :

// 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)

데모


크로스 플랫폼 개발자의 경우 (참고 지금까지 제공된 모든 답변은 iOS에서 작동하지 않습니다) :

마우스 업 / 다운은 안드로이드 에서 제대로 작동하는 것처럼 보이지만 모든 장치 (예 : 삼성 탭 4)는 아닙니다. iOS 에서는 전혀 작동하지 않았습니다 .

추가 연구는 이것이 선택 요소와 기본 배율이 청취자를 방해하기 때문인 것으로 보입니다.

이 이벤트 리스너는 사용자가 500ms 동안 이미지를 보유한 경우 썸네일 이미지를 부트 스트랩 모달로 열 수 있도록합니다.

반응 형 이미지 클래스를 사용하므로 더 큰 버전의 이미지가 표시됩니다. 이 코드는 (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)
});

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

데모


Diodeus의 답변은 훌륭하지만 onClick 기능을 추가 할 수 없으므로 onclick을 넣으면 보류 기능을 실행하지 않습니다. Razzak의 대답은 거의 완벽하지만 마우스 업에서만 홀드 기능을 실행하며 일반적으로 사용자가 계속 누르고 있어도 기능이 실행됩니다.

그래서 나는 둘 다 합류하여 이것을 만들었습니다.

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

이를 통해 각 요소는 자체 시간 초과를 얻습니다.


최신 모바일 브라우저의 경우 :

document.addEventListener('contextmenu', callback);

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


jquery-mobile의 taphold를 사용할 수 있습니다. jquery-mobile.js를 포함하면 다음 코드가 정상적으로 작동합니다.

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

Most elegant and clean is a jQuery plugin: https://github.com/untill/jquery.longclick/, also available as packacke: https://www.npmjs.com/package/jquery.longclick.

In short, you use it like so:

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

The advantage of this plugin is that, in contrast to some of the other answers here, click events are still possible. Note also that a long click occurs, just like a long tap on a device, before mouseup. So, that's a feature.


For me it's work with that code (with 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);

You can check the time to identify Click or 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);
}
} 

like this?

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

You can use jquery Touch events. (see here)

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

I needed something for longpress keyboard events, so I wrote this.

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

참고URL : https://stackoverflow.com/questions/2625210/long-press-in-javascript

반응형