Bootstrap 4 - 使下拉菜单的父项保持可点击 link

Bootstrap 4 - Keeping Parent of Dropdown a clickable link

<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/

例如,点击男装系列可将您带到该区域的所有系列。但是在下拉菜单中,您可以继续选择特定的项目。

我正在尝试以主父导航会显示项目的方式实现它。项目的下拉菜单会显示每个项目的特定页面,例如项目 1、项目 2 等。但是单击“项目”会将您带到一个页面,其中项目 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>

<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.To 显示下拉菜单显示下拉菜单只需将打开 class 添加到 <li class="nav-item dropdown">

Using CSS, Using Jquery

我尽量保持代码简单。我的解决方案是检测下拉菜单 button/link 上的第二次点击,然后在该点点击 link。

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

这在折叠视图中也有效。

我接受了 Joe 的回答并根据我的需要对其进行了改进

/*
 * 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>

最简单的方法是从父元素中删除 "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>

所以,从本质上讲,我只是简单地删除了数据切换属性,从而将悬停下拉菜单转换为具有可点击父级的悬停下拉菜单 link。

这是我的解决方案。这个想法是检测用户点击下拉菜单 button/link 的 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;
    }
  });

这也适用于折叠视图(移动)。

可点击下拉菜单 link 在 Bootstrap 4

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

所以父 href link 将正常工作,但当用户单击加号图标时,它将打开下拉菜单。

/* -----------------------------------------------------------------------
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>

//Fix bootstrap dropdown parent click
let clicked = 0;
document.querySelector('.dropdown-toggle').addEventListener('click',(e)=>{    
    clicked++;
    if(clicked > 1 && e.target.classList.contains('show')){
        location.href = e.target.href
        clicked = 0;
    }
})

简单 javascript 唯一的解决方案,如果下拉列表包含打开的 class.

,第二次单击父项将重定向到位置