javascript - 在不使用窗口和文档对象的情况下在外部单击时隐藏 div

标签 javascript html css

如何隐藏 <div>当我使用 onblur 在其外部单击时?我尝试使用下面的代码,但是当我单击复选框时它会消失,而当我在它外面单击时它不会消失。

然后我尝试使用 windowdocument可以工作,但我当前使用的平台不支持的对象。我正在使用 Lightning 平台

这是否可以使用 JavaScript 和/或 CSS 实现?

var expanded = false;

function showshow() {
  var show = document.getElementById("show");

  if (!expanded) {
    show.style.display = "block";
    expanded = true;
  } else {
    show.style.display = "none";
    expanded = false;
  }
}

function hideshow() {
  var show = document.getElementById("show");

  if (expanded) {
    show.style.display = "none";
    expanded = false;
  }
}
#show {
  position: absolute;
  width: 200px;
  display: none;
  border: 1px solid #000000;
  background-color: #ffffff;
}

#show label {
  display: block;
  white-space: nowrap;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}

#show label:hover {
  background-color: #eff1f4;
}
<form id="input-form">
  <button type="button" onclick="showshow()">Select an option</button>

  <div id="show" tabindex="1" onblur="hideshow()">
    <label for="OptionA">
<input type="checkbox" id="OptionA" value="Option A" />Option A</label>
    <label for="OptionB">
<input type="checkbox" id="OptionB" value="Option B" />Option B</label>
    <label for="OptionC">
<input type="checkbox" id="OptionC" value="Option C" />Option ABCDEFGHIJKLMNOPQRSTUVWXYZ</label>
  </div>
</form>

最佳答案

document.getElementsByTagName("body")[0].addEventListener("click", function(){
  if(event.target.parent.id !== "idOfYourDiv") {
    // call hideshow() function
  }
});

关于javascript - 在不使用窗口和文档对象的情况下在外部单击时隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108841/

相关文章:

javascript - 输出变量到html

javascript - 滚动到 DataTables jQuery 插件中选定的行

javascript - Webpack 通天塔 6

javascript - 捕捉 "Display forbidden by X-Frame-Options”

javascript - Fancybox 内容颜色

javascript - jquery 编辑链接 href 如果 body class = x

jquery - 使用 Jquery 添加大块 HTML

javascript - html2canvas 无法加载未定义的图像

php - 我在我的文件夹中找不到 bootstrap.css

jquery - 设置新元素的位置,同时悬停元素