我想将自动对焦添加到表单中。这工作正常,但对于搜索表单,我还使用显示状态更改,从无到阻止再返回。
第一次自动对焦工作正常,但隐藏表格并再次显示后,自动对焦功能不再有效。
有没有办法通过jQuery实现这一目标?我需要什么代码?
HTML:
<div class="header-search">
<div class="search-container">
<div class="overwrite-setting">
<i class="sf-icon-search"></i>
</div>
<div class="switcher-content">
<form id="search_mini_form" action="https://www.redable.nl/catalogsearch/result/" method="get">
<div class="form-search">
<input id="search" autofocus="autofocus" placeholder="Zoeken naar..." type="text" name="q" value="" class="input-text" maxlength="128" autocomplete="off">
<button type="submit" title="Zoek" class="search-button"><span><span><i class="fa fa-search"></i></span></span></button>
<div id="search_autocomplete" class="search-autocomplete" style="display: none;"></div>
</div>
</form>
</div>
</div>
</div>
jQuery的:
jQuery('.header-setting .overwrite-setting').click(function() {
jQuery('.setting-switcher .switcher-content').toggle();
jQuery(this).toggleClass('active');
return false;
})
if(jQuery(window).width() > 1024){
jQuery('.header-maincart .icon-cart-header').click(function() {
jQuery('.header-maincart .cart-wrapper').toggle();
jQuery(this).toggleClass('active');
return false;
})
}
jQuery('.header-search .overwrite-setting').click(function() {
jQuery('.search-container .switcher-content').toggle();
jQuery(this).toggleClass('active');
return false;
})
jQuery(document).mouseup(function (e)
{
if(jQuery(window).width() > 1024){
if(jQuery('.header-maincart').has(e.target).length == 0 && jQuery('.cart-wrapper').has(e.target).length == 0 ){
jQuery('.header-maincart .cart-wrapper').hide();
jQuery('.header-maincart .icon-cart-header').removeClass('active');
}
}
if(jQuery('.header-search .overwrite-setting').has(e.target).length == 0 && jQuery('.search-container .switcher-content').has(e.target).length == 0){
jQuery('.search-container .switcher-content').hide();
jQuery('.header-search .overwrite-setting').removeClass('active');
}
if(jQuery('.header-setting .overwrite-setting').has(e.target).length == 0 && jQuery('.setting-switcher .switcher-content').has(e.target).length == 0){
jQuery('.setting-switcher .switcher-content').hide();
jQuery('.header-setting .overwrite-setting').removeClass('active');
}
});
答案 0 :(得分:1)
不确定如何隐藏/显示input
,但您可以在显示后使用元素上的focus
函数:
$('button').click(function() {
$('#search').toggle().focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" autofocus="autofocus" placeholder="Zoeken naar..." type="text" name="q" value="" class="input-text" maxlength="128" autocomplete="off">
<button>Click to hide/show the button</button>