2011-09-23 85 views
0

可能重複:
JQuery slideToggle timeoutJQuery的顯示/隱藏面板

我有簡單的HTML頁面:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 

    <script> 
     $(document).ready(function() { 

      $("div").hide(); 

      $("button").hover(function() { 
       $("div").slideDown("slow"); 
      }); 

      setTimeout(hidepanel, 4000); 

      function hidepanel() { 
       if ($('div').is(':hover') === false) { 
        $('div').slideUp(); 
       } 
      } 

      $('div').mouseleave(function() { setTimeout(hidepanel, 4000); }); 
      $('button').mouseleave(function() { setTimeout(hidepanel, 4000); }); 
     }); 
    </script> 

    <style> 
    div { width:400px; } 
    </style> 
</head> 
<body> 
    <button>Toggle</button> 
    <div style="border: 1px solid"> 

    This is the paragraph to end all paragraphs. You 
    should feel <em>lucky</em> to have seen such a paragraph in 
    your life. Congratulations! 
    </div> 
</body> 
</html> 

我需要:

  1. 顯示面板(DIV),而鼠標光標位於按鈕或通過面板(DIV)
  2. 隱藏面板時鼠標還沒有結束按鈕或面板4秒
  3. 隱藏面板立即當我在頁面上點擊面板或按鈕外的任何地方。

我該怎麼改變我的代碼?

非常感謝!

+0

爲什麼不能一下子問這個問題:http://stackoverflow.com/questions/7528503/ –

+0

爲什麼要重新發明輪子?爲什麼不使用像clueTip這樣的現有jQuery插件? –

+0

Kalle H.Väravas - 我很抱歉,但不同的問題和不同的解決方案 – ihorko

回答

1

http://jsfiddle.net/TQp9C/1/

有趣的部分點擊面板/按鈕的外側時,隱藏面板。

$(document).click(function (e) {  
    if (e.target.id !== "btn" && e.target.id !== 'panel' && $(e.target).parents('#panel').length === 0) 
    { 
     hidepanel(); 
    } 
});