2011-09-23 82 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(); 
    } 
});