我使用 javascript 通过 onclick 显示 div,但是当我单击 div 外部时,我想隐藏 div。
经过更多搜索,我找到了一个功能,并且效果很好
但是有一个问题,代码需要第一次双击才能显示潜水
我的代码:
<script>
// click on the div
function toggle( e, id ) {
var el = document.getElementById(id);
el.style.display = ( el.style.display == 'none' ) ? 'block' : 'none';
// save it for hiding
toggle.el = el;
// stop the event right here
if ( e.stopPropagation )
e.stopPropagation();
e.cancelBubble = true;
return false;
}
// click outside the div
document.onclick = function() {
if ( toggle.el ) {
toggle.el.style.display = 'none';
}
}
</script>
<style>#tools{display:none;}</style>
<div id="tools">Hidden div</div>
<a href="#" onclick="toggle(event, 'tools');">show/hide</a>
这是我的完整代码,你可以在你的电脑上测试。
问题是:该功能需要单击两次,我想在单击时显示 div(单击)而不是(双击)