jquery - 如何获取上一个焦点元素?

标签 jquery focus selector

如何获取上一个焦点元素?

说明:

当用户单击手机键盘按键时,它不应被激活或聚焦。 这样: 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/

相关文章:

$(this).find (':nth-child(2)' 上的 jquery 选择器混合)

visual-studio-code - 如何修复我的 sass 编译错误 : expected selector

jquery - 如何仅在 iframe 中查看时隐藏元素

从索引链接加载页面时,Javascript 未加载

javascript - 使用 "this"onblur 后 jQuery 焦点

jquery - 获取一个 HTML 元素

javascript - 有一个简单但有用的 jquery.JsPlumb 示例吗?

jquery - 叠加点击交互问题

android - 如何在android中显示对图像onclick的关注?

Xamarin Forms - 当不存在输入控件时,物理键盘会使页面变暗