change div color on mouseenter during timeout - jquery function

邮差的信 提交于 2019-12-11 21:26:45

问题


Right now I have this code:

$('.a').mouseenter(function(){
    var $this =  $(this);
    clearTimeout($this.data('timerMouseleave'));
    $this.css('border', 'solid 1px #444444')
}).mouseleave(function(){
    var $this =  $(this);
    var timer = setTimeout($.proxy(function(){
        $this.css('border', 'solid 1px #dddddd')
    }, this), 1000)
    $this.data('timerMouseleave', timer)
}).click(function(){
    var $this =  $(this);
    $this.css('border', 'solid 1px black')
    $this.off('mouseenter mouseleave');
})

http://jsfiddle.net/7dXAs/6/

I want to add the red border only in case of entering the div again while the timeout is still on. (if possible, please also include playing sound in this case, for ex. aaa.wav).

I need to keep the rest of this behavior exactly as it is, which means that red border should normally change back to default after the timeout.

clarification:

timeout / delay gets triggered after mouseleave and it lasts 1 second.

  • current situation: if you enter the div again before 1 second expires, timeout gets removed and then triggered again after another mouseleave
  • wanted situation: if you enter the div again before 1 second expires, border becomes red, timeout gets removed and then triggered again after another mouseleave

回答1:


Try

$('.a').mouseenter(function(){
    var $this =  $(this);
    clearTimeout($this.data('timerMouseleave'));
    if($this.hasClass('hide-timer')){
        $this.css('border', 'solid 1px red')
    } else {
        $this.css('border', 'solid 1px #444444')
    }
}).mouseleave(function(){
    var $this =  $(this);
    var timer = setTimeout($.proxy(function(){
        $this.css('border', 'solid 1px #dddddd').removeClass('hide-timer')
    }, this), 1000)
    $this.data('timerMouseleave', timer).addClass('hide-timer')
}).click(function(){
    var $this =  $(this);
    $this.css('border', 'solid 1px black')
    $this.off('mouseenter mouseleave');
})

Demo: Fiddle



来源:https://stackoverflow.com/questions/18463981/change-div-color-on-mouseenter-during-timeout-jquery-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!