如何获取上一个焦点元素?
说明:
当用户单击手机键盘按键时,它不应被激活或聚焦。 这样: focus 或 activeElement 返回前一个焦点元素(textarea 或 input-text)。
<script>
$(function(){
$(".phonepad").prop("disabled", true);
$('.phonepad').mousedown(function() { preventDefault();});
$('.phonepad input').mousedown(function() { preventDefault();});
$('.phonepad input').click(function(){
$(document.activeElement).sendkeys(
this.name || this.value);
);
});
});
</script>
<div class="phonepad" >
<input type="button" value="7" ><br>
<input type="button" value="4" ><br>
</div><br/>
<input type="text" class="output" /><br/>
<textarea class="output"></textarea><br/>
最佳答案
您可以使用隐藏元素来跟踪具有当前焦点的元素。这样,当另一个元素获得焦点时,它将保留前一个元素的 id。当单击启用焦点的元素时,其 id 会存储在隐藏元素中。单击禁用焦点的元素时,焦点将放回到先前获得焦点的元素上,并且“active_focus_enabled_id”隐藏元素不会更新。您需要使用类来识别哪些元素能够/无法接收焦点,并确保所有启用焦点的元素都有一个 id。
<input type='hidden'id='active_focus_enabled_id' value=''id_with_initial_focus'>
<input type='button' class='focus_enabled' id='id_with_initial_focus' value='Whatever #1'>
<input type='button' class='focus_enabled' id='some_other_id' value='Whatever #2'>
...
<input type='button' class='focus_disabled' value='Phone Input #1'>
<input type='button' class='focus_disabled' value='Phone Input #2'>
...
<script>
$('.focus_disabled').click(function(event) {
var id_previous = $('active_focus_enabled_id' ).val();
$(''#' + id_previous).focus();
});
$('.focus_enabled').click(function(event) {
var id_new = $(event.target).attr('id');
$('active_focus_enabled_id').val(id_new);
});
</script>
关于jquery - 如何获取上一个焦点元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9651532/