这个问题不是微不足道的,但是根据这个答案,可以通过以下方式解决:
HTML
<textarea id="example1" onfocus="focushandler('divID1');"></textarea>
<br />
<textarea id="example2" onfocus="focushandler('divID2');"></textarea>
<br />
<div id="divID1">
<p>This div is blue</p>
<br />
<input type="checkbox" />Checkbox A
</div>
<div id="divID2">
<p>This div is green</p>
<br />
<input type="checkbox" />Checkbox B
</div>
Javascript
var current = null; //currently shown div - divID1 or divID2
function focushandler(id) {
if (current !== null) {
current.style.display = 'none';
}
var div = document.getElementById(id);
div.style.display = 'block';
current = div;
}
function clickhandler(e) {
if (current == null) { //if both divs are hidden
return;
}
e = e || window.event; //for IE8,7 compatibility
var t = e.target || e.srcElement; // clicked element
var sig = false;
// now check all parents
while (t) {
if (t === current || t.nodeName == 'TEXTAREA') {
sig = true;
}
t = t.parentNode;
}
if (sig) {
return;
}
current.style.display = 'none';
current = null;
}
if (document.documentElement.addEventListener) {
document.documentElement.addEventListener('click', clickhandler, false);
} else if (document.documentElement.attachEvent) { // for IE8-7 compatibility
document.documentElement.attachEvent('onclick', clickhandler);
}
JSFiddle: http: //jsfiddle.net/PfQfN/4/(适用于 Firefox、Chrome、IE7-10、Safari 和 Opera)。或者你也可以使用这个稍微修改过的代码:http: //jsfiddle.net/PfQfN/6/(效果是一样的)。
更新的 CSS:根据这个非常有用的答案,这些元素可以更好地定位,如下所示: http : //jsfiddle.net/PfQfN/9/