0

我刚开始 Web 编程,但 addEventListener 有问题。

我做了一个翻转卡片动画,当您单击容器中的任何位置时,卡片翻转并显示一些信息的背面,包括 2 个超链接。

我的问题是当我点击这些链接时,卡片再次翻转。因此,当我仅单击这两个链接时,我想避免卡片翻转,但它仍应在容器上的其他任何地方工作。我已经尝试过 StopImmediate 传播和 prevetdefault 但它似乎不起作用。你能帮我吗?

对不起我的英语不好,这不是我的母语。

我的JS:

 document.getElementById("d2_container").addEventListener('click', function () {
                this.classList.toggle('turnY');
            });

HTML:

 <section id="d2_container">
            <article>
                <img src="img/photo2.png" alt="">
            </article>
            <article>
                <h3 class="coordonnée">Coordonnées</h3>
                <div>
                    <p>Adresse : ########</p>
                    <p>Téléphone : ########</p>
                    <p>Email : <a href="####@outlook.fr">####@outlook.fr</a>
                    </p>
                    <p>Permis B et vehicule.</p>
                    <div>
                    <a href="https://www.lequipe.fr/Football/" target="_blank"><i class="fab fa-linkedin-in"></i></a>
                    <a href=""><i class="fab fa-github"></i></a>
                    </div>

                </div>
            </article>
        </section>
4

1 回答 1

1

检查事件target是否有<a>祖先,如果有,不要继续该函数:

document.getElementById("d2_container").addEventListener('click', function ({ target }) {
  if (target.closest('a')) {
    return;
  }
  this.classList.toggle('turnY');
});

document.getElementById("d2_container").addEventListener('click', function({ target }) {
  if (target.closest('a')) {
    return;
  }
  this.classList.toggle('turnY');
  console.log('toggled');
});
<section id="d2_container">
  <article>
    <img src="img/photo2.png" alt="">
  </article>
  <article>
    <h3 class="coordonnée">Coordonnées</h3>
    <div>
      <p>Adresse : ########</p>
      <p>Téléphone : ########</p>
      <p>Email : <a href="####@outlook.fr">####@outlook.fr</a>
      </p>
      <p>Permis B et vehicule.</p>
      <div>
        <a href="https://www.lequipe.fr/Football/" target="_blank"><i class="fab fa-linkedin-in"></i></a>
        <a href=""><i class="fab fa-github"></i></a>
      </div>

    </div>
  </article>
</section>

(如果您<a>的 s 没有孩子,您可以改为检查 if target.tagName === 'A'

于 2019-01-29T09:56:45.720 回答