问题
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