Bootstrap 4 - 让Dropdown的父级成为可点击链接

时间:2018-02-16 05:08:53

标签: javascript html css twitter-bootstrap-4

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

Bootstrap新手。这是基于Bootstrap示例的代码。现在,下拉列表显示但您无法单击下拉列表本身。我希望能够使所有父导航链接工作。与此网站类似:https://eastcfashion.com/

点击例如:men's collection将带您进入该区域的所有收藏。但是下拉菜单中,您可以继续使用特定项目。

我正试图以主父导航说项目的方式实现它。项目的下拉菜单会显示每个项目的特定页面,如项目1,项目2等。但是单击项目会将您带到项目1,项目2和项目集合将作为一组显示的页面而不是单独的。

7 个答案:

答案 0 :(得分:6)

最简单的方法是从父元素中删除“ data-toggle”属性! 编辑:技巧,这是一个代码示例: 我改变了这个:

<a class="p-2 text-dark dropdown-toggle" data-toggle="dropdown" style="font-size:1.25rem;" href= {% url 'link' %}>Link</a>

对此:

<a class="p-2 text-dark dropdown-toggle" style="font-size:1.25rem;" href= {% url 'link' %}>Link</a>

因此,从本质上讲,我只是删除了数据切换属性,然后将可悬停下拉列表转换为带有可点击父链接的可悬停下拉列表。

答案 1 :(得分:2)

jQuery(function($) {
  if ($(window).width() > 769) {
    $('.navbar .dropdown').hover(function() {
      $(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();

    }, function() {
      $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp();

    });

    $('.navbar .dropdown > a').click(function() {
      location.href = this.href;
    });

  }
});
@media only screen and (min-width:769px) {
  .dropdown:hover .dropdown-menu {
    display: block;
  }
  .dropdown-submenu {
    position: relative !important;
  }
  .dropdown-submenu>.dropdown-menu {
    top: 0 !important;
    left: 100% !important;
    margin-top: -6px !important;
    margin-left: -1px !important;
    border-radius: 0 !important;
  }
  .dropdown-submenu:hover>.dropdown-menu {
    display: block !important;
  }
  .dropdown-submenu>a:after {
    display: block;
    content: "\f105";
    font-family: 'FontAwesome';
    margin-top: -18px;
    right: 15px;
    position: absolute;
    font-weight: 300;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://v4-alpha.getbootstrap.com/dist/js/bootstrap.min.js"></script>
<link href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="#">Navbar</a>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li><li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown link
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

答案 2 :(得分:2)

我试图保持代码简单。我的解决方案是检测第二次单击下拉按钮/链接,然后点击该链接。

$('.navbar .dropdown > a').click(function() {
 if (!$(this).hasClass("parent-clicked")) {
    $(this).addClass("parent-clicked");
  } else {
    location.href = this.href;
  }
});

这在折叠视图中也有效。

答案 3 :(得分:1)

我接受了乔的回答,并将其改进为我的需要

/*
 * Only go to the link when dropdown is already open (if the dropdown is a link)
 */
$('.navbar ul.navbar-nav > .dropdown > a[href]').click(function() {
    var dropdown = $(this).next('.dropdown-menu');
    /*
     * The dropdown can be non-existent
     * The dropdown can be already open by css
     * (for instance display: block from a custom :hover setting) 
     * or a "show" class on the element which also sets a display: block;
     */
    if (dropdown.length == 0 || $(dropdown).css('display') !== 'none') {
        if (this.href) {
            location.href = this.href;
        }
    }
});

Bootstrap 4的html是

<header class="navbar"> 
    <ul class="nav navbar-nav">            
        <li class="nav-item dropdown">
            <a class="nav-link" href="/planning" data-toggle="dropdown">
                Planning
            </a>
            <ul class="dropdown-menu">
                <li class="dropdown-item">
                    <a href="/day-planning">Day planning</a>
                </li>
            </ul>
        </li>
    </ul>
</header>

答案 4 :(得分:1)

Bootstrap 4 中可点击的下拉链接

我隐藏了原来的下拉三角形图标,并制作了一个新的加号图标,因为原来的图标很小,而且是用伪类:after制作的,用户很难将光标指向并点击它。

因此父 href 链接将正常工作,但当用户单击加号图标时,它将打开下拉列表。

/* -----------------------------------------------------------------------
Make Bootstrap dropdown "a" link clickable
But when clicking plus icon, show the dropdown
--------------------------------------------------------------------------- */
function clickableDropdownLink() {

    if (window.matchMedia("(max-width: 992px)").matches) {
        const dropdownToggle = $('.navbar .dropdown > a');
        dropdownToggle.append('<span class="dropdown-icon"></span>');
        dropdownToggle.removeAttr('data-toggle');

        $('.navbar .dropdown > a').click(function(e) {
            e.preventDefault();
            if ((e.target.tagName == 'A')) {
                const route = $(this).attr("href");
                window.location.href = route == '/' || route == '#' ? window.location.href : route;
                return;
            }
        })

        const dropdownIcon = $('.navbar .dropdown > a > span.dropdown-icon');
        dropdownIcon.click(function() {
            const parentLink = $(this).parent("a.nav-link");
            parentLink.parent(".nav-item").toggleClass("show");
            parentLink.next(".dropdown-menu").toggle();
        })

    }
}


clickableDropdownLink();


/* ------------------------------------------------------------------------------------
This is optional, this could make your app slower
 If you want to make a dropdown link clickable after user resizing screen, you can add this. This could make your app slower
 ----------------------------------------------------------------------------------------- */
$(window).resize(function() {
    clickableDropdownLink();
})



/* ------------------------------------------------------------------------------------
This is optional
If you also want the dropdown link work in Desktop size. 
----------------------------------------------------------------------------------------- */

if (window.matchMedia("(min-width: 992px)").matches) {
    $('.navbar .dropdown > a').click(function() {
        location.href = this.href;
    });
}
.dropdown .dropdown-icon{
      display: none;
            position: absolute;
            padding: 15px;
            background: #fff;
            right: 10px;
            top: 8px;
}

.dropdown .dropdown-icon:before{
  transition: all ease 0.5s;
                background: #444;
                height: 2px;
                width: 16px;
                top: 14px;
                left: 7px;
                content: "";
                position: absolute;
}
.dropdown .dropdown-icon:after{
  transition: all ease 0.5s;
                    background: #444;
                    content: "";
                    height: 16px;
                    left: 14px;
                    position: absolute;
                    top: 7px;
                    width: 2px;
}

.dropdown.show .dropdown-icon:after{
    transform:rotate(-90deg);
}

.dropdown.show .dropdown-icon:before{
   transform:rotate(-180deg);
}

.navbar .dropdown .dropdown-toggle .dropdown-icon{
     display:none;
 }

@media(max-width:992px){
  .navbar .dropdown .dropdown-toggle::after{
     display:none;
  }
  .navbar .dropdown .dropdown-toggle .dropdown-icon{
     display:block;
  }
  .navbar .dropdown .dropdown-menu .dropdown-item{
      white-space:pre-wrap;
  }
}
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Clickable Dropdown Link</title>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css'><link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
 <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="https://www.google.com" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown1
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action 1</a>
          <a class="dropdown-item" href="#">Another action 1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here 1</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="https://www.google.com" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown 
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>
<!-- partial -->
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.1/umd/popper.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js'></script><script  src="./script.js"></script>

</body>
</html>

答案 5 :(得分:0)

<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>

此代码段切换下拉菜单,但点击事件和href用于切换下拉菜单。所以根据你的需要 -

将href重定向到常规项目页面并添加悬停事件以使用jquery或CSS显示下拉菜单。要显示下拉菜单,只需将开放类添加到<li class="nav-item dropdown">

<强> Using CSS 下, 的 Using Jquery

答案 6 :(得分:0)

这是我的解决方案。这个想法是检测用户单击下拉按钮/链接上的area并重定向到该URL。

  // clickable dropdown menu parent
  $('.navbar .dropdown > a').on('click', function(e) {
    let elementBegin = $(this).offset()['left']; // get link position X

    // get the width of the menu by text's length
    // you need to contain the text inside a span tag
    let spanWidth = $(this).find("> span").width();
    let clickAreaLength = spanWidth * 0.9; // 90% of width = clickable area

    let clickPositionX = e.pageX; // position of the click

    // if click position is inside the clickable area, then redirect
    if (clickPositionX < elementBegin + clickAreaLength) {
      location.href = this.href;
    }
  });

这在折叠视图(移动设备)中也适用。