如何在鼠标单击标签外时关闭详细信息标签

Cai*_*uke 1 html css

<details>当用户单击标签之外的某个位置时,如何取消展开标签?

我想没有 CSS 解决方案,所以 JavaScript 解决方案就可以了。

谢谢。

Spe*_*ric 5

您可以添加一个事件侦听器来click检查事件目标是否是标记的子级,如果不是,则删除该open属性:

var details = document.querySelector('details');
document.addEventListener('click', function(e){
  if(!details.contains(e.target)){
    details.removeAttribute('open')
  }
})
Run Code Online (Sandbox Code Playgroud)
details{
  border:1px solid;
}
Run Code Online (Sandbox Code Playgroud)
<details>
  <summary>Click to open</summary>
  <p>Click somewhere else (not this) to close the dropdown</p>
</details>
Run Code Online (Sandbox Code Playgroud)
如果您有多个detail标签,则可以使用querySelectorAll以下方法选择所有元素并判断是否在标签外部单击了一个元素Array#some

var details = [...document.querySelectorAll('details')];
document.addEventListener('click', function(e){
  if(details.some(f => f.contains(e.target)).length != 0){
    details.forEach(f => f.removeAttribute('open'));
  }
})
Run Code Online (Sandbox Code Playgroud)
details{
  border:1px solid;
}
Run Code Online (Sandbox Code Playgroud)
<details>
  <summary>Click to open</summary>
  <p>Click somewhere else (not this) to close the dropdown</p>
</details>

<details>
  <summary>Click to open 2</summary>
  <p>Click somewhere else (not this) to close the dropdown</p>
</details>

<details>
  <summary>Click to open 3</summary>
  <p>Click somewhere else (not this) to close the dropdown</p>
</details>
Run Code Online (Sandbox Code Playgroud)