2013-10-09 52 views
2

我想改變div的顏色
當鼠標離開這個div然後不回5sec在這個div然後改變div背景顏色
這裏是一些代碼,以使從DIV
如果在5秒後將鼠標移出div,然後改變div的顏色,那麼改變div的顏色

<html> 
<head> 
    <meta charset="utf-8" /> 
    <title>jQuery UI Effects - Animate demo</title> 
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
    <style> 
    #effect { width: 240px; padding: 0.4em; position: relative; background: yellow; } 
    </style> 
    <script> 
    var sec = 0; 
     function pad (val) { return val > 9 ? val : "0" + val; } 
     setInterval(function(){ 
      $("#effect").attr("name",pad(++sec%60)); 
     }, 1000); 
     $(document).ready(function(){ 
     $("#effect").mouseout(function(){ 
      var time = $(this).attr("name"); 
      alert("at Mouse out:- "+time+" Second "); 
     }); 
     }); 
    </script> 
</head> 
<body> 
    <div id="effect" class="ui-widget-content ui-corner-all">ON Ready Status... 
</div> 
</body> 
</html> 
<script> 
</script> 

我怎樣才能改變DIV顏色5秒後獲得最後的鼠標出去的時間。鼠標掉了?

+4

使用'的setTimeout()'代替 – Morpheus

+1

看到http://jsfiddle.net/arunpjohny/WLhpU/3/ –

回答

2
$("#test").on('mouseenter', function() { 
     $("#test").css('background-color', 'red'); 
    }); 


    $("#test").on('mouseleave', function() { 
      var timer=self.setInterval(function() { 
      $("#test").css('background-color', 'blue'); 
      window.clearInterval(timer);},5000); 
    }); 
}); 

小提琴:http://jsfiddle.net/jsAgX/

1

使用接下來5秒

setTimeout(function() { 
//your code 
},5000); 
1

後運行代碼嘗試

#effect.mouseout { 
    background: red; 
} 

$(document).ready(function() { 
    $("#effect").hover(function() { 
     var $this = $(this) 
     clearTimeout($this.data('mouseouttimer')); 
     $this.removeClass('mouseout'); 
    }, function() { 
     var $this = $(this) 
     var timer = setTimeout(function() { 
      $this.addClass('mouseout'); 
     }, 2000); 
     $this.data('mouseouttimer', timer); 
    }).trigger('mouseleave'); 
}); 

演示:Fiddle