[英]Hide div when clicked outside without using window and document object
当我使用onblur
点击外面时,如何隐藏<div>
? 我尝试使用下面的代码,但是当我单击复选框时它会消失,当我点击它之外时,它不会消失。
然后我尝试使用window
或document
对象,但我目前正在使用的平台不支持。 我正在使用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
}
});
$(document).click(function(event) { //if you click on anything except the modal itself or the "open modal" link, close the modal if (!$(event.target).closest(".modal,.js-open-modal").length) { $("body").find(".modal").removeClass("visible"); } });
在展开时使show
集中,隐藏onblur
后记:
var expanded = false; function showshow() { var show = document.getElementById("show"); if (!expanded) { show.style.display = "block"; show.focus(); // make show focused expanded = true; } else { show.style.display = "none"; expanded = false; } } function hideshow() { var show = document.getElementById("show"); if (expanded) { setTimeout(() => { show.style.display = "none"; expanded = false; }, 100); } }
#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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.