Bootstrap 4 - 将下拉菜单的父级保持为可点击的链接

Posted

技术标签:

【中文标题】Bootstrap 4 - 将下拉菜单的父级保持为可点击的链接【英文标题】:Bootstrap 4 - Keeping Parent of Dropdown a clickable link 【发布时间】:2018-07-26 23:41:08 【问题描述】:
<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 示例的代码。现在下拉列表显示,但您无法单击下拉列表本身。我希望能够使所有父导航链接正常工作。类似本站:https://eastcfashion.com/

点击例如:男士系列将您带到该区域的所有系列。但是下拉菜单,你可以只选择特定的项目。

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

【问题讨论】:

我认为您希望下拉菜单出现在悬停...对..? 【参考方案1】:

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>

【讨论】:

您的下拉菜单无法正常工作...当我从下拉链接中下拉时,下拉菜单消失了 我已在本地服务器上尝试过此代码。请将此代码复制到您的文件中。它工作正常。实际上他希望父菜单可链接。 当你打开 js fiddle JS 脚本在刷新后没有加载它工作正常。因此,请在您的文件中更新此代码。可以看到jsfiddle.net/htmlguruz/odz25mL7再次打开刷新页面。谢谢【参考方案2】:
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>

这个 sn-p 切换下拉菜单,但在点击事件和 href 用于切换下拉菜单。所以根据你的需要-

将href重定向到通用项目页面并添加悬停事件以使用jquery或CSS显示下拉菜单。要显示下拉菜单只需将open class添加到&lt;li class="nav-item dropdown"&gt;

Using CSS, Using Jquery

【讨论】:

【参考方案3】:

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

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

这也适用于折叠视图。

【讨论】:

如果有人想在第一次点击上工作,只需删除 if 语句。我的意思是只留下location.href = this.href;【参考方案4】:

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

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

【讨论】:

【参考方案5】:

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

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

【讨论】:

确保写上如何做的代码,所以 answer = result =)【参考方案6】:

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

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

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

【讨论】:

【参考方案7】:

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>

【讨论】:

【参考方案8】:
//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解决方案,如果下拉菜单包含开放类,第二次点击父级将重定向到位置。

【讨论】:

以上是关于Bootstrap 4 - 将下拉菜单的父级保持为可点击的链接的主要内容,如果未能解决你的问题,请参考以下文章

单击关闭时保持 Bootstrap 下拉菜单打开

在内部单击时保持 Bootstrap 下拉菜单打开

mouseenter 上的 angular-bootstrap 下拉菜单,并在单击之前保持下拉菜单隐藏。

点击时保持 Bootstrap 下拉菜单打开

Bootstrap 下拉菜单 - 如果搜索栏被聚焦,则保持打开状态

Bootstrap 3下拉菜单中心对齐不起作用