【问题标题】:How to close details tag when other is open or a click is made outside the tag当其他标签打开或在标签外点击时如何关闭详细信息标签
【发布时间】:2021-10-09 03:28:54
【问题描述】:

下面的这段代码几乎可以解决问题。如果您打开任何详细信息标签,然后单击它之外的任何位置,它将关闭。但是,当前打开的详细信息标签不会在新的详细信息标签打开时关闭。

var details = [...document.querySelectorAll('details')];
document.addEventListener('click', function(e) {
  if (!details.some(f => f.contains(e.target))) {
    details.forEach(f => f.removeAttribute('open'));
  }
})
<details>
  <summary>Details 1</summary>
  <p>content</p>
</details>

<details>
  <summary>Details 2</summary>
  <p>content</p>
</details>

<details>
  <summary>Details 3</summary>
  <p>content</p>
</details>

我错过了什么?

谢谢。

【问题讨论】:

    标签: html details-tag


    【解决方案1】:

    可以检查目标是否为details标签,如果不是,关闭所有details标签。

    如果是,只关闭那些没有作为子事件目标的事件。

    var details = [...document.querySelectorAll('details')];
    document.addEventListener('click', function(e) {
      if (!details.some(f => f.contains(e.target))) {
        details.forEach(f => f.removeAttribute('open'));
      } else {
        details.forEach(f => !f.contains(e.target) ? f.removeAttribute('open') : '');
      }
    })
    <details>
      <summary>Details 1</summary>
      <p>content</p>
    </details>
    
    <details>
      <summary>Details 2</summary>
      <p>content</p>
    </details>
    
    <details>
      <summary>Details 3</summary>
      <p>content</p>
    </details>

    【讨论】:

    • 为什么要删除之前的回答?只需按照您所说的删除条件,它似乎就可以正常工作。
    • 哦,我现在明白了。对于前一个标签,即使您在其中单击,标签也会关闭。这个新的似乎也解决了这个问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多