javascript 如何正确使用bootstrap 5.3弹出框?

jk9hmnmh  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(170)

我正在尝试创建一个web与一堆popover,让我们说:

<a tabindex="0" data-bs-toggle="popover">popover 1</a>
<a tabindex="0" data-bs-toggle="popover">popover 2</a>

而内容是:

<div id="content1" class="bs-none">
   <p>very long content for popover1</p>
</div>

<div id="content2" class="bs-none">
   <p>very long content for popover2</p>
</div>

问题是,如何创建那些弹出显示它自己的内容与最少的脚本?
要实现目标是用最少的脚本激活弹出相同或不同的内容

9wbgstp7

9wbgstp71#

你可以添加content div的id作为trigger a元素的data属性:

document.addEventListener('DOMContentLoaded', () => {
  const elems = document.querySelectorAll('[data-bs-toggle="popover"]');

  const popovers = [...elems].map(el => new bootstrap.Popover(el, {
trigger: 'focus',
html: true,
content: document.getElementById(el.dataset.contentId)?.innerHTML || ''
  }));
});
body, html {
      height: 100%;
    }

    .popover-container {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      gap: 20px;
    }
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/js/bootstrap.min.js" integrity="sha384-heAjqF+bCxXpCWLa6Zhcp4fu20XoNIA98ecBC1YkdXhszjoejr5y9Q77hIrv8R9i" crossorigin="anonymous"></script>
<div class="popover-container">
  <a tabindex="0" data-bs-toggle="popover" data-content-id="content1">popover 1</a>
  <a tabindex="0" data-bs-toggle="popover" data-content-id="content2">popover 2</a>
</div>
<div id="content1" class="bs-none">
  <p>very long content for popover1</p>
</div>
<div id="content2" class="bs-none">
  <p>very long content for popover2</p>
</div>

相关问题