[英]focusout on a input form and div
I'm trying to make a dropdown suggestion box. 我正在尝试制作下拉建议框。 In that case I wish to hide the box whenever the input field AND dropdown box is no longer in focus.
在这种情况下,只要输入字段AND下拉框不再处于焦点位置,我就希望隐藏该框。
This is my HTML code: 这是我的HTML代码:
<input type="text" id="user_address">
<div id="user_address_sg">SUGGESTION</div>
<div id="another element">Pressing another element on the page should hide the suggestion box</div>
I have tried the following: 我尝试了以下方法:
$('[id=user_address][id=user_address_sg]').focusout(function (){
$('#user_address_sg').hide();
});
How come the user_address_sg
doesn't hide whenever I select another input field or other elements on the page? 每当我选择页面上的另一个输入字段或其他元素时,
user_address_sg
不会隐藏?
Images (1st: When I write a name, 2nd: When I select another form while suggestions appear) 图片(第一个:当我写名字时;第二个:当我在显示建议时选择另一种形式)
First image: suggestion box should be displayed and clickable 第一张图片:建议框应显示并单击
Second image: When doing this the suggestion box should disappear 第二张图片:执行此操作时,建议框应消失
UPDATED: CSS alternative: 更新: CSS替代:
function suggest(key) { document.getElementById('user_address').value = document.getElementById(key).innerHTML; }
#user_address_sg { vertical-align: top; text-decoration: none; display: none; color:black; } #user_address_sg:focus, #user_address_sg:active { display: inline-block; color:black; } #user_address:focus ~ #user_address_sg { display: inline-block; }
<input type="text" id="user_address"> <a href=# id="user_address_sg"> <span id=a1 onClick="suggest('a1')">SUGGESTION 1</span><br> <span id=a2 onClick="suggest('a2')">SUGGESTION 2</span><br> <span id=a3 onClick="suggest('a3')">SUGGESTION 3</span><br> <span id=a4 onClick="suggest('a4')">SUGGESTION 4</span> </a>
You may need blur
and separate the selectors with commas, because one single element with two different ids doesn't exist, but two different elements with different ids yes. 您可能需要
blur
并用逗号分隔选择器,因为不存在具有两个不同ID的单个元素,但是两个具有不同ID的不同元素是。 So separate them: 因此,将它们分开:
$('[id=user_address],[id=user_address_sg]').blur(function (){
$('#user_address_sg').hide();
});
Better with on()
method 使用
on()
方法更好
$('[id=user_address],[id=user_address_sg]').on('blur', function (){
$('#user_address_sg').hide();
});
blur
event will fire when a focused element loses the focus. 当聚焦的元素失去焦点时,
blur
事件将触发。 So I think that's what you need. 所以我认为这就是您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.