【问题标题】:Trap mouseup event only if occur after 1 second of mousedown仅在 mousedown 1 秒后发生时捕获 mouseup 事件
【发布时间】:2014-11-10 06:12:05
【问题描述】:

在我的项目中,我需要在 mouseup 事件中执行一些操作,但前提是他的 mousedown 至少在一秒钟后。 我试过这个:

$('*').on('mousedown', function (e) {
// make sure the event isn't bubbling
if (e.target != this) {
    return;
}
  //some code
}

var delay = 1000;
var timeout = null;
$(window).on('mouseup', function (e) {

    clearTimeout(timeout);
    timeout = setTimeout(function(){
        // do something
    },delay);
});

但是这种方式的mouseup事件并不是与mousedown相关联的,而是对自己进行的。 如何确保我的代码仅在用户按住至少一秒钟后释放鼠标按钮时才执行??

谢谢大家

【问题讨论】:

    标签: javascript jquery timeout mouseevent


    【解决方案1】:

    钩住mousedown并记录它发生的时间:

    var mousedown;
    $(document).on("mousedown", function() {
        mousedown = Date.now();
    });
    

    挂起 mouseup 看看是否至少过了一秒:

    $(document).on("mouseup", function() {
        var elapsed = Date.now() - mousedown;
        mousedown = undefined;
        if (elapsed >= 1000) {
            // A second or more
        }
    });
    

    var mousedown;
    
    $(document).on("mousedown", function() {
      mousedown = Date.now();
      snippet.log("Down at " + new Date().toISOString());
    });
    
    $(document).on("mouseup", function() {
      var elapsed = Date.now() - mousedown;
      snippet.log("Up at " + new Date().toISOString());
      mousedown = undefined;
      if (elapsed >= 1000) {
        // A second or more
        snippet.log("A second or more (" + elapsed + ")");
      } else {
        snippet.log("Less than a second (" + elapsed + ")");
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    在上面,我在document 上挂上了 mousedown,但如果您有充分的理由将其挂接到问题中的每个单独元素上,您可以根据需要进行调整。


    真正旧的浏览器上,Date.now 将不存在。您可以轻松地对其进行 polyfill:

    if (!Date.now) {
        Date.now = function() {
            return +new Date();
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-12
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多