How to have a mouseover event fire only if the mouse is hovered over an element for at least 1 second?

前端 未结 4 1801
渐次进展
渐次进展 2020-12-02 15:46

I want to display a dialog when a user mouses over a certain image. That part works. Unfortunately if the mouse even just passes over the corner of the image quickly it will

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 16:36

    You can't delay the firing of the event, but you can delay your handling of the event.

    Here's a quick example without jQuery or Prototype that will make it easier to understand.

    var delay = function (elem, callback) {
        var timeout = null;
        elem.onmouseover = function() {
            // Set timeout to be a timer which will invoke callback after 1s
            timeout = setTimeout(callback, 1000);
        };
    
        elem.onmouseout = function() {
            // Clear any timers set to timeout
            clearTimeout(timeout);
        }
    };
    
    
    delay(document.getElementById('someelem'), function() {
        alert("Fired");
    });
    

提交回复
热议问题