【问题标题】:Click outside menu to close it with jQuery单击外部菜单以使用 jQuery 将其关闭
【发布时间】:2018-06-18 18:17:31
【问题描述】:

我想在不使用 event.stopPropagation() 的情况下通过单击菜单外部(包括打开菜单的链接)来关闭菜单。

jQuery

$('a').click(function() {
  if ($(this).next().is(':visible')) $(this).next().hide();
  else $(this).next().show();
});
$(document).click(function(e) {
  if ($(e.target).is('a, ul'))  return false;
  else $('ul').hide();
}); 

CSS

td { padding:20px; }
ul { display:none; position:absolute; background:yellow; padding:10px; }

HTML

<table>
<tr>
<td><a href="#">show</a><ul>list 1</ul></td>
<td><a href="#">show</a><ul>list 2</ul></td>
<td><a href="#">show</a><ul>list 3</ul></td>
</tr>
</table>

http://jsfiddle.net/d8o6L71g/

此代码的唯一问题是,当我单击打开另一个菜单时,其他菜单仍保持打开状态。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您需要明确说明您希望菜单何时消失。你先把所有的东西都隐藏起来怎么样? http://jsfiddle.net/d8o6L71g/3/

      $('a').click(function() {
        if ($(this).next().is(':visible'))
        {
        	$(this).next().hide();
        }
        else
        {
          $('a').next().hide();
          $(this).next().show();
        }
        
      });
      $(document).click(function(e) {
        if ($(e.target).is('a, ul'))
        {
          return false;
        }
        else 
        {
          $('ul').hide();
        }
      }); 
    td { padding:20px; }
    ul { display:none; position:absolute; background:yellow; padding:10px; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    
    
    <table>
    <tr>
    <td><a href="#">show</a><ul>list 1</ul></td>
    <td><a href="#">show</a><ul>list 2</ul></td>
    <td><a href="#">show</a><ul>list 3</ul></td>
    </tr>
    </table>

    【讨论】:

    • 谢谢乔希。它工作正常,但我忘了提到我在菜单中有链接,当我点击它们时,我也不希望菜单关闭。任何解决方案将不胜感激。
    • 当然@tahoma 您可以使用ID 来定位您想要打开和关闭的目标。如果您可以更新您的 html 以反映您拥有的内容,我可以帮助提供解决方案。谢谢!
    • 这是我将在页面上使用的表格示例,右侧列中的链接下方有下拉菜单(此处仅第一行中的单元格 6、7、9)。由于大量的链接和菜单,我认为 ID 不实用。是否不可能在脚本中以某种方式使用 td > div 以便打开菜单内的链接在单击时不会导致它关闭? jsfiddle.net/d8o6L71g/17
    • 我想通了,将第一个选择器从“a”更改为“td > a”。再次感谢。
    • 好消息@tahoma!祝你编码好运。
    猜你喜欢
    • 2016-04-24
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    相关资源
    最近更新 更多