当我使用<div>
单击onblur
时如何隐藏它?我尝试使用下面的代码,但是当我单击复选框时,它消失了;当我单击它之外时,它也不会消失。
然后我尝试使用有效的window
或document
对象,但当前使用的平台不支持该对象。
使用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>
答案 0 :(得分:0)
如果您不能在平台上使用addEventListener
,则可以尝试attachEvent
在旧平台上完成这项工作。
例子:
if (document.addEventListener) { // For all major browsers, except IE 8 and earlier
document.addEventListener("click", myFunction);
} else if (document.attachEvent) { // For IE 8 and earlier versions
document.attachEvent("onclick", myFunction);
}
最诚挚的问候:)
答案 1 :(得分:0)
在文档主体上触发hideshow
事件时,您将必须调用click
函数,然后检查事件的目标是否为document.body
:
var expanded = false;
function showshow(event) {
var show = document.getElementById("show");
if (!expanded) {
show.style.display = "block";
expanded = true;
} else {
show.style.display = "none";
expanded = false;
}
}
function hideshow(event) {
var show = document.getElementById("show");
var elem = event.target;
// Check if the event's target is the document's body
if(elem && elem.id == "main") {
show.style.display = "none";
expanded = false;
}
}
document.body.onclick = hideshow;
html,
body,
#main {
height: 100%;
width: 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;
}
<main id="main">
<button type="button" id="toggle-modal" onclick="showshow(event)">Select an option</button>
<div id="show" tabindex="1" onblur="hideshow(event)">
<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>
</main>