【问题标题】:Hide item when background container is clicked using jQuery使用 jQuery 单击背景容器时隐藏项目
【发布时间】:2016-01-29 21:20:23
【问题描述】:

我正在创建的这个菜单的一切都很完美,除了一件事。单击主导航项并打开子菜单时,关闭子菜单的唯一方法是再次单击相同的主导航项。我想这样做,如果用户单击主弹出窗口中的其他任何位置,子菜单将关闭。

请参阅下面的代码 sn-p 了解我的确切代码:

<!doctype html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="">
<!--<![endif]-->

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="apple-touch-icon" href="apple-touch-icon.png">

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  <style>
    body {
      padding-top: 50px;
      padding-bottom: 20px;
    }
  </style>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
</head>

<body>
  <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->


  <!--MAIN CONTENT GOES HERE -->

  <style>
    /* main menu */
    .mainNav {
      margin: 0;
      padding: 0;
      min-height: 100px;
      text-align: left;
      white-space: normal;
      width: 368px;
      display: block;
      cursor: default;
    }
    .mainNav-item {
      display: inline-block;
      vertical-align: top;
    }
    .mainNav-item a {
      text-decoration: none;
      color: black;
    }
    .mainNav-item a:hover {
      text-decoration: none;
      color: black;
    }
    .mainNav-item-tile {
      display: block;
      margin: 6px 5px 6px 5px;
      padding: 0;
      text-align: center;
      line-height: normal;
      position: relative;
      text-decoration: none;
      width: 110px;
      height: 110px;
      background: transparent;
      border-width: 0;
      font-size: 14px;
      outline-color: #e7e7e7;
      background-color: #e7e7e7;
    }
    .mainNav-item-tile:hover {
      outline-color: #ccc;
      background-color: #ccc;
    }
    .mainNav-item-tile-img {
      display: block;
      padding: 15px;
      margin-left: auto;
      margin-right: auto;
    }
    .popover {
      max-width: 600px;
      width: auto;
    }
    /* The container <div> - needed to position the dropdown content */
    .dropdown {
      position: relative;
      display: inline-block;
    }
    /* Dropdown Content (Hidden by Default) */
    .dropdown-content {
      display: none;
      position: absolute;
      background-color: #f9f9f9;
      min-width: 160px;
      box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
      z-index: 1000;
      left: 80px;
      top: 20px;
    }
    /* Links inside the dropdown */
    .dropdown-content a {
      color: black;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
    }
    /* Change color of dropdown links on hover */
    .dropdown-content a:hover {
      background-color: #f1f1f1
    }
  </style>



  <div style="float: left; cursor: pointer; margin: 13px 15px 0 0">
    <img data-toggle="popover" data-placement="bottom" onmouseover="this.src='http://placehold.it/32x32'" onmousedown="this.src='http://placehold.it/32x32'" onmouseout="this.src='http://placehold.it/32x32'" src="http://placehold.it/32x32" />

    <div id="popover_content_wrapper" style="display: none;">
      <div>
        <ul class="mainNav">
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem1</span>
            </a>

            <div id='content1' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem2</span>
            </a>

            <div id='content2' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem3</span>
            </a>

            <div id='content3' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem4</span>
            </a>

            <div id='content4' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem5</span>
            </a>

            <div id='content5' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>





  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


  <script type="text/javascript">
    $(document).ready(function() {
                $('[data-toggle="popover"]').popover({
                    html: true,
                    content: function () {
                        return $('#popover_content_wrapper').html();
                    }
                });

                $('html').on('click', function (e) {
                    $('[data-toggle="popover"]').each(function () {
                        //the 'is' for buttons that trigger popups
                        //the 'has' for icons within a button that triggers a popup
                        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                            $(this).popover('hide');
                        }
                    });
                });

                $("html").on("click", ".dropdown", function (e) {
                    var $this = $(this).children(".dropdown-content");

                    if ($this.find("a").length > 0) {
                        e.preventDefault();

                        $(".dropdown-content:visible").not($this).slideToggle(200); //Close submenu already opened
                        $this.slideToggle(200); //Open the new submenu
                    }
                });
    });
  </script>


</body>

</html>

【问题讨论】:

  • 在小提琴中设置它,比如 jsfiddle.org 并发布链接
  • 那么你想点击包含五个项目的菜单中的空白区域并能够关闭弹出框吗?

标签: javascript jquery html css twitter-bootstrap


【解决方案1】:

在单击时将关闭事件添加到父级,并在单击子级时停止事件传播。

将此添加到您的代码中:

$('html').on('click', ".mainNav", function(e) {
    $(".dropdown-content:visible").slideToggle(200);
});

并在下面添加e.stopPropagation();

$("html").on("click", ".dropdown", function(e) {

Here is the JSFiddle demo

【讨论】:

  • 谢谢你这完美的作品。知道为什么当我单击子菜单中的一个锚点时我没有导航到任何地方吗?有什么可能取消它吗?
  • 是的,这是因为您的代码中的e.preventDefault(); 会在找到链接时触发
  • 谢谢!我最终弄清楚它创建另一个 $("html").on("click", ".dropdown-content a", function(e) { 以停止传播,如果实际单击锚标记使其永远不会冒泡处理子菜单打开和关闭的事件。
【解决方案2】:

您可以添加一个额外的if 来处理这个问题。

if(!$(e.target).parents('.dropdown').length){
    $('.dropdown-content').hide();
}

这就是说,“如果被点击的东西的父母有一个dropdown类,那么隐藏任何.dropdown-content的”。

您可以将hide 更改为slideUp,或任何您喜欢的。

您发布的代码可以用于优化。将事件连接到$(document)&lt;html&gt; 是一种不好的做法——您应该将它附加到您知道将存在的最低级别的元素上。对你来说,这至少可以是ul.mainNav

<!doctype html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="">
<!--<![endif]-->

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="apple-touch-icon" href="apple-touch-icon.png">

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  <style>
    body {
      padding-top: 50px;
      padding-bottom: 20px;
    }
  </style>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
</head>

<body>
  <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->


  <!--MAIN CONTENT GOES HERE -->

  <style>
    /* main menu */
    .mainNav {
      margin: 0;
      padding: 0;
      min-height: 100px;
      text-align: left;
      white-space: normal;
      width: 368px;
      display: block;
      cursor: default;
    }
    .mainNav-item {
      display: inline-block;
      vertical-align: top;
    }
    .mainNav-item a {
      text-decoration: none;
      color: black;
    }
    .mainNav-item a:hover {
      text-decoration: none;
      color: black;
    }
    .mainNav-item-tile {
      display: block;
      margin: 6px 5px 6px 5px;
      padding: 0;
      text-align: center;
      line-height: normal;
      position: relative;
      text-decoration: none;
      width: 110px;
      height: 110px;
      background: transparent;
      border-width: 0;
      font-size: 14px;
      outline-color: #e7e7e7;
      background-color: #e7e7e7;
    }
    .mainNav-item-tile:hover {
      outline-color: #ccc;
      background-color: #ccc;
    }
    .mainNav-item-tile-img {
      display: block;
      padding: 15px;
      margin-left: auto;
      margin-right: auto;
    }
    .popover {
      max-width: 600px;
      width: auto;
    }
    /* The container <div> - needed to position the dropdown content */
    .dropdown {
      position: relative;
      display: inline-block;
    }
    /* Dropdown Content (Hidden by Default) */
    .dropdown-content {
      display: none;
      position: absolute;
      background-color: #f9f9f9;
      min-width: 160px;
      box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
      z-index: 1000;
      left: 80px;
      top: 20px;
    }
    /* Links inside the dropdown */
    .dropdown-content a {
      color: black;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
    }
    /* Change color of dropdown links on hover */
    .dropdown-content a:hover {
      background-color: #f1f1f1
    }
  </style>



  <div style="float: left; cursor: pointer; margin: 13px 15px 0 0">
    <img data-toggle="popover" data-placement="bottom" onmouseover="this.src='http://placehold.it/32x32'" onmousedown="this.src='http://placehold.it/32x32'" onmouseout="this.src='http://placehold.it/32x32'" src="http://placehold.it/32x32" />

    <div id="popover_content_wrapper" style="display: none;">
      <div>
        <ul class="mainNav">
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem1</span>
            </a>

            <div id='content1' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem2</span>
            </a>

            <div id='content2' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem3</span>
            </a>

            <div id='content3' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem4</span>
            </a>

            <div id='content4' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
          <li class="mainNav-item dropdown" data-toggle="popover" data-placement="bottom">
            <a ID="navItem" runat="server" class="mainNav-item-tile">
              <img width="64" height="64" src="http://placehold.it/64x64" class="mainNav-item-tile-img" />
              <span>MainMenuItem5</span>
            </a>

            <div id='content5' class='dropdown-content'>
              <a href='#'>SubMenuItem1</a>
              <a href='#'>SubMenuItem2</a>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>





  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


  <script type="text/javascript">
    $(document).ready(function() {
                $('[data-toggle="popover"]').popover({
                    html: true,
                    content: function () {
                        return $('#popover_content_wrapper').html();
                    }
                });

                $('html').on('click', function (e) {
                   if(!$(e.target).parents('.dropdown').length){
                        $('.dropdown-content').hide();
                   }
                    $('[data-toggle="popover"]').each(function () {
                        //the 'is' for buttons that trigger popups
                        //the 'has' for icons within a button that triggers a popup
                        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                            $(this).popover('hide');
                        }
                    });
                });

                $("html").on("click", ".dropdown", function (e) {
                    var $this = $(this).children(".dropdown-content");

                    if ($this.find("a").length > 0) {
                        e.preventDefault();

                        $(".dropdown-content:visible").not($this).slideToggle(200); //Close submenu already opened
                        $this.slideToggle(200); //Open the new submenu
                    }
                });
    });
  </script>


</body>

</html>

【讨论】:

    【解决方案3】:

    将此添加到 $(document).ready() 内的 javascript 代码中

    $("html").on("click", ".mainNav", function (e) {
        if(e.target.className == "mainNav"){
            $(".dropdown-content:visible").slideToggle(200);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 2019-03-09
      • 1970-01-01
      相关资源
      最近更新 更多