为了账号安全,请及时绑定邮箱和手机立即绑定

长期在JavaScript?

长期在JavaScript?

慕尼黑8549860 2019-08-15 17:23:10
长期在JavaScript?是否可以在JavaScript(或jQuery)中实现“长按”?怎么样?HTML<a href="" title="">Long press</a>JavaScript的$("a").mouseup(function(){   // Clear timeout   return false;}).mousedown(function(){   // Set timeout   return false; });
查看完整描述

3 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

没有'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; });


查看完整回答
反对 回复 2019-08-15
?
aluckdog

TA贡献1847条经验 获得超7个赞

根据Maycow Moura的回答,我写了这个。它还确保用户不会进行右键单击,这会触发长按并在移动设备上运行。DEMO

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


查看完整回答
反对 回复 2019-08-15
?
慕斯709654

TA贡献1840条经验 获得超5个赞

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

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


查看完整回答
反对 回复 2019-08-15
  • 3 回答
  • 0 关注
  • 462 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信