当输入出现时,我没有自动对焦。 自动对焦属性在 Chrome 上会间歇性地起作用。 在 IE11 上...它甚至不会尝试添加它。
在使用 jQuery 应用自动对焦之前,我是否需要验证 DOM 上输入元素是否存在?
HTML5
<input type="text" class="form-control" autofocus placeholder="Filter">
JS
function iboxHistorySearch() {
var header = $('.client-history .ibox-title_replace'),
searchbar = $('.client-history .client-history-searchbar'),
closeBtn = $('.client-history .btn-dismiss');
header.on('click', function (e) {
e.preventDefault();
if (searchbar.hasClass('hidden')) {
searchbar.removeClass('hidden')find('form-control:first').focus();
$(this).addClass('hidden');
}
});
closeBtn.on('click', function (e) {
e.preventDefault();
if (header.hasClass('hidden')) {
header.removeClass('hidden');
searchbar.addClass('hidden');
}
});
}
iboxHistorySearch();
更新
searchbar.removeClass('hidden')find('form-control:first').focus();
最佳答案
来自(未经编辑的)问题:
var searchbar = $('.client-history .client-history-searchbar')
if (searchbar.hasClass('hidden')) {
searchbar.removeClass('hidden').focus();
确保搜索栏是一个可以接收焦点的输入
控件。如果没有,请添加 .find
来获取输入,可以是第一个元素,也可以是特定元素,例如:
searchbar.removeClass('hidden')
.find('.form-control:first')
.focus();
或
searchbar.removeClass('hidden')
.find('input:first')
.focus();
(但使用输入
,您可能还需要添加复选框/选择等,例如)
searchbar.removeClass('hidden')
.find('input,select,textarea')
.first()
.focus();
关于javascript - 当 elem 出现时,自动对焦无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40507923/