我有一个隐藏的搜索字段,当用户点击搜索图标时,它会打开,我想立即将焦点带到搜索输入,这样用户就不必再点击两次.它在Chrome中完美运行,但在Safari(桌面)中则不行.我看到了其他一些建议,将它包装在超时中会起作用,但仍然没有骰子.有什么想法吗?
jQuery的:
$search = $('.header--search-container');
$searchInput = $('.header--search-input input[type=search]');
$search.click(function(){
$searchInput.toggleClass('search-active');
setTimeout(function(){
$('header .header--search-input .search-field').focus();
}, 1);
});
HTML(不要认为它是必需的,但你可以看到……另外编辑的是< header>元素):
<div class="header--search-input">
<form role="search" method="get" class="search-form" action="http://example.com/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s" />
</label>
<input type="submit" class="search-submit" value="Search" />
</form>
</div>
<div class="header--search-container">
<svg>
.. redacted for legibility on stack overflow ..
</svg>
</div>
最佳答案 添加更高的setTimeout值有效.
$search.click(function(){
$searchInput.toggleClass('search-active');
setTimeout(function(){
$('header .header--search-input .search-field').focus();
}, 500);
});