首页 > 解决方案 > 如何在鼠标点击标签时关闭详细信息标签

问题描述

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

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

谢谢你。

标签: htmlcss

解决方案


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

var details = document.querySelector('details');
document.addEventListener('click', function(e){
  if(!details.contains(e.target)){
    details.removeAttribute('open')
  }
})
details{
  border:1px solid;
}
<details>
  <summary>Click to open</summary>
  <p>Click somewhere else (not this) to close the dropdown</p>
</details>
如果您有多个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'));
  }
})
details{
  border:1px solid;
}
<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>


推荐阅读