首页 > 解决方案 > 仅在单击时加载选项卡内容

问题描述

我正在尝试解决如何仅在单击而不是之前加载我的选项卡的内容。每次切换到另一个选项卡时,我都需要重新加载内容,这是因为我需要在每个选项卡中嵌入自动播放的视频,并且我需要重新加载,这样视频就不会在后面继续播放。而且我需要每次只播放一个视频。我已经尝试了很多东西,此时我没有任何我认为它会起作用的东西。

现在我的标签的代码如下:

const tabSystem = {
  init() {
    document.querySelectorAll('.tabs-menu').forEach(tabMenu => {
      Array.from(tabMenu.children).forEach((child, ind) => {
        child.addEventListener('click', () => {
          tabSystem.toggle(child.dataset.target);
        });
        if (child.className.includes('is-active')) {
          tabSystem.toggle(child.dataset.target);

        }
      });
    });
  },
  toggle(targetId) {
    document.querySelectorAll('.tab-content').forEach(contentElement => {
      contentElement.style.display = contentElement.id === targetId ? 'block' : 'none';
      document.querySelector(`[data-target="${contentElement.id}"]`).classList[contentElement.id === targetId ? 'add' : 'remove']('is-active');
    })
  },
};
tabSystem.init();
margin: 0;
font-size: 0;
padding: 0;

}
.tabs-menu {
  cursor: pointer;
  font-family: 'Inter', sans-serif;
}
.tab-item {
  font-size: 15px;
  background-color: #A6B7C7;
  display: inline-block;
  padding: 13px 20px;
  color: white;
  margin: 0;
}
.is-active {
  color: black;
}
.tab-content {
  display: none;
  padding: 0px;
}
.show-content {
  display: block;
  background: lightgray;
}
<ul class="tabs-menu">
  <li class="tab-item is-active" data-target="first-tab"><a>Español</a></li>
  <li class="tab-item" data-target="second-tab" id="Tab02"><a>English</a></li>
  <li class="tab-item" data-target="third-tab"><a>Português</a></li>
</ul>

<div class="tab-content" id="first-tab">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/7N9XW_mQ7hI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

<div class="tab-content" id="second-tab">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/bdvidv6RXJY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

<div class="tab-content" id="third-tab">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/rSnaEd-dwTg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

如果有人知道如何解决这个问题,我将不胜感激。

标签: javascripthtmliframetabsreload

解决方案


删除 DOM 中每个 iFrame 的 src 并通过 javascript 将它们设置为选项卡单击。以下是添加和删除源的方法。为每个 iFrame 提供 Id 或根据单击的选项卡查找 iFrame 并添加源并删除所有其他 iframe 的源。或者只是全局删除 iFrame 的所有源并将源添加到所需的框架。

//ADD SOURCE
document.getElementById('first').src = 'https://www.youtube.com/embed/7N9XW_mQ7hI';
//REMOVE SOURCE
document.getElementById('first').src = '';

推荐阅读