首页 > 解决方案 > Bootstrap 4:在折叠的手风琴卡片中创建指向 ID 的直接链接,然后打开卡片并跳转到 ID

问题描述

我想创建一个指向折叠卡内的 ID 的链接(引导程序 4)。当我单击链接时 - 应该打开卡并跳转到 ID。

我试过了:www.link.com#linktoidinsidecollapsedcard但这并没有打开折叠的卡片。

有任何想法吗?

更新说明

虽然我想对#ourElement另一个页面的元素 ID 进行相同的滚动,但使用类似的链接<a href="//thisismysite.com/subpage/item.php#ourElement">Link on the block 3 inside ID</a>

标签: javascripthtmljquerytwitter-bootstrapbootstrap-4

解决方案


对于这个任务,我们需要一个关于 jQuery 的小脚本。您的链接应该有类.accordionLink,并且看起来像这样。右侧的文本是我们所需元素的 ID。#href<a href="#ourElement" class="accordionLink">...</a>#

<div id="ourElement"><b>Our element</b></div>根据#3放入里面。尝试单击链接Link on the block 3 inside ID。我只是在开始时有一个 ling,另一个在 Block #1 内。两者都有效。您可以根据需要在任何地方使用与类匹配的链接.accordionLink

脚本中有注释,所以你会明白的。

// better to use some class like '.accordionLink' and check a link for it so other links with '#' will work as they should, without a conflict
$('a[href*="#"].accordionLink').click(function (e) {		
  e.preventDefault();
  let desiredId = $.attr(this, 'href').split('#')[1]; //getting data from the left and right from #, and calling the right one by '[1]'  
  // checking if element with this ID exists
  if ($('#'+desiredId).length ) {
    // showing the closes parent '.collapse' of our ID
    $('#'+desiredId).closest('.collapse').collapse('show'); 
    setTimeout(function () {
      // smooth animation to our ID
      $('html, body').animate({
        scrollTop: $('#'+desiredId).offset().top
      }, 500);
    }, 300); // this interval is necessary for bootstrap to complete the accordion animation
  }		
});
/* not necessary */
body {
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script>

<a href="#ourElement" class="accordionLink">Link on the block 3 inside ID</a>

<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>
      </h2>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body">
        <a href="#ourElement" class="accordionLink">Link on the block 3 inside ID</a><br> 
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.        
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </button>
      </h2>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </button>
      </h2>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        <div id="ourElement"><b>Our element</b></div>
        rd dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

更新

添加了if (location.hash)我们在 URL 中查找哈希的部分。现在,如果您将使用地址打开页面//thisismysite.com/subpage/item.php#ourElement- 此代码将查找#ourElement它是否位于.collapse. <a href="//thisismysite.com/samepage#ourElement">在同一页面上使用/samepage是完全可以的,它只会触发脚本而不会重新加载页面。而且您不需要class="accordionLink"来自另一个页面的链接。

// looking for hash in URL
if (location.hash) {
  let desiredHash = window.location.hash.split('#')[1]; //getting data from the left and right from #, and calling the right one by '[1]'  
  desiredFunction(desiredHash); // calling function and sending hash
}

// better to use some class like '.accordionLink' and check a link for it so other links with '#' will work as they should, without a conflict
$('a[href*="#"].accordionLink').click(function (e) {		
  e.preventDefault();
  let linkId = $.attr(this, 'href').split('#')[1]; //getting data from the left and right from #, and calling the right one by '[1]'  
  desiredFunction(linkId); // calling function and sending hash
});

function desiredFunction(desiredId) {
  // checking if element with this ID exists and if the element inside of accordion
  //if (($('#'+desiredId).length) && ($('#'+desiredId).closest('.collapse').length)) {
  if (($('#'+desiredId).length) && ($('#'+desiredId).closest('.collapse').length)) {
    // showing the closes parent '.collapse' of our ID
    $('#'+desiredId).closest('.collapse').collapse('show'); 
    setTimeout(function () {
      // smooth animation to our ID
      $('html, body').animate({
        scrollTop: $('#'+desiredId).offset().top
      }, 500);
    }, 300); // this interval is necessary for bootstrap to complete the accordion animation
  }	
}
/* not necessary */
body {
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script>

<a href="#ourElement" class="accordionLink">Link on the block 3 inside ID</a>

<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
              Collapsible Group Item #1
            </button>
      </h2>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body">
        <a href="#ourElement" class="accordionLink">Link on the block 3 inside ID</a><br> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.
        Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente
        ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
              Collapsible Group Item #2
            </button>
      </h2>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
              Collapsible Group Item #3
            </button>
      </h2>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        <div id="ourElement"><b>Our element</b></div>
        rd dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt
        sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>


推荐阅读