javascript 如何使用 onfocus 显示和隐藏 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3586546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to show and hide a div using onfocus
提问by Mike
i'm sorta new to this. i have this so far:
我对这个有点陌生。到目前为止我有这个:
<style type="text/css">
#show_hide{display:none;}
</style>
<div id="show_hide">
ok
</div>
<input type="text" onfocus="document.getElementById('show_hide').style.display='block';">
it works when i click the input box to show the div. prob is i need it to hide again when i click somewhere else or "unfocus" any help? thanks!
当我单击输入框以显示 div 时,它会起作用。问题是当我点击其他地方或“不聚焦”任何帮助时,我需要它再次隐藏吗?谢谢!
回答by STW
So, your issue is that your CSS sets the default state of the div (to display:none), then your JavaScript changes the state onfocus to display: block--but you don't have any code to revert the div back to the hidden state.
因此,您的问题是您的 CSS 将 div 的默认状态设置为 (to display:none),然后您的 JavaScript 将状态 onfocus 更改为 --display: block但您没有任何代码将 div 恢复为隐藏状态。
With plain JavaScript I believe you'll want the onblurevent (focus lost) to handle this:
使用普通的 JavaScript,我相信你会希望onblur事件(焦点丢失)来处理这个:
<input type="text"
onfocus="document.getElementById('show_hide').style.display='block';"
onblur="document.getElementById('show_hide').style.display='none';">
回答by Alex
have you tried leveraging onblur event http://javascript.gakaa.com/div-blur-4-0-5-.aspx
您是否尝试过利用 onblur 事件http://javascript.gakaa.com/div-blur-4-0-5-.aspx
also this post might help How to blur the div element?
这篇文章也可能有助于如何模糊 div 元素?
回答by GotDibbs
The event handler you are looking for is called onBlur (http://www.w3schools.com/jsref/event_onblur.asp).
您正在寻找的事件处理程序称为 onBlur ( http://www.w3schools.com/jsref/event_onblur.asp)。

