我有一个动画搜索栏,当用户点击它以外的地方时,它会隐藏起来。然而,这会导致直接单击旁边的提交按钮被忽略。我该如何解决这个问题?
HTML,
<form role="search" id="searchform" method="get" action="/">
<i class="icon icon-search"></i>
<a id="search-toggle" href="#"></a>
<input type="submit" value="">
<input id="search" type="text" name="s" value="">
</form>
CSS (SCSS),
form {
margin: 0;
input {
float: right;
}
input[type="text"] {
height: 3rem;
margin: 5px 0 0 0;
padding: 0;
width: 0;
@include transition(all, .2s, ease-in-out);
&.active {
width: 80%;
padding: .5rem 1rem;
}
}
input[type="submit"] {
width: 4rem;
background-color: transparent;
}
}
a, i {
position: absolute;
line-height: 4rem;
width: 4rem;
height: 4rem;
text-align: center;
top: 0;
right: 0;
}
i {
pointer-events: none;
color: $light-grey;
font-size: 1.6rem;
z-index: 30;
padding: 3px 0 0 0;
@include transition(color, .2s, ease);
}
JS,
$('#search').focusout(function() {
$(this).removeClass('active');
});
还尝试使用 blur() 而不是 focusout(),结果相同。
编辑:添加了一些额外的代码。我有一个图标和不可见的链接按钮覆盖提交按钮以防止它立即提交 - 我想首先动画并显示搜索框。在显示该框并且用户输入内容后,这是我在到达提交事件时遇到麻烦的时候。现在需要点击两次,第一次关闭框,然后第二次触发按钮。
最佳答案
我知道这是一个老问题,但碰巧我遇到了同样的问题并以其他方式解决了它,所以也许下面的代码对其他人来说很方便:
$('#text_input_id').blur(function(event){
//event.relatedTarget gets the object that triggered the blur event(or "focus
// out" event), in this case if it is a submit input, ignore the blur event.
if($(event.relatedTarget).prop('type') === 'submit'){
event.preventDefault();
}
else {
//Do whatever you want when focusing out. For instance:
$('#search').css('display', 'none');
}
});
¿为什么这有效?
focusout
或 blur
事件(查看差异 here )确实会阻止提交按钮正常工作,因为某些它如何覆盖 submit
事件,然后导致单击两次提交的奇怪行为。这里的技巧是使用 event.relatedTarget
, 它获取触发 blur
的对象事件。在这种情况下,如果它是任何提交按钮 <input type="submit" value="Search">
), 然后调用 event.preventDefault()
解决此问题。
关于jquery - Focusout 功能否定点击提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26997846/