我正在开发一个场景,用户可以在隐藏元素中选择一个输入。当该输入被聚焦时,我希望它的父元素,隐藏元素,使用jQuery显示。到目前为止,我似乎无法让这个工作。
这就是我的HTML:
<div class="select">
<input tabindex="1" type="text" name="search" class="address" id="address-1" placeholder="Tab to the next input.">
<div class="dropdown">
<div class="dropdown-search">
<input tabindex="2" type="text" name="search" class="search" id="dropdown-search-1" placeholder="Type to search...">
</div>
</div>
和jQuery:
$('.select').each(function() {
var dropdown = $('.dropdown', this),
search = $('.search', this);
search.focus(function() {
dropdown.show();
});
});
我也把我的代码放在这里:http://jsfiddle.net/ae26u/1/
答案 0 :(得分:5)
解决这个问题的一个技巧是将元素隐藏在屏幕之外,而不是实际隐藏在DOM之外。
如果它在屏幕外隐藏,它仍然是“绘制”的,因此您可以选中它,然后在标签上将其移回屏幕。
jQuery的:
$('.select').each(function() {
var dropdown = $('.dropdown', this),
search = $('.address', this);
dropdown.focus(function() {
console.log('show');
dropdown.css( "left", "0px" )
});
});
HTML:
<div class="select">
<input tabindex="1" type="text" name="search" class="address" id="address-1" placeholder="Tab to the next input."><br />
<input tabindex="2" type="text" name="search" class="dropdown" id="dropdown-search-1" placeholder="Type to search...">
</div>
jsFiddle示例:http://jsfiddle.net/ae26u/7/
答案 1 :(得分:1)
您无法使用Tab键聚焦隐藏元素。但是你可以用javascript来触发它。
示例:
$('.select .address').keydown(function(event) {
// 9 == tab key code
if (event.keyCode == 9) {
// Find the dropdown ...
var dropdown = $(this).parent().find('.dropdown');
// ... and show it
dropdown.show();
// Focus the input in the dropdown
dropdown.find('.search').focus();
return false;
}
})
使用此代码,当您点击可见输入上的标签时,我们会显示隐藏的输入,然后我们将其关注。