移至网页的第一个"默认"焦点

use*_*855 9 html javascript css jquery

假设您有网站,当您刷新它时,如果您检查哪个元素具有焦点,请使用以下代码:

setInterval(function () {
    console.log('ID: ', $(document.activeElement).attr('id') + ' Tag: ' + $(document.activeElement).prop('tagName')
        + ' C: ' + $(document.activeElement).attr('class'));
}, 2000);
Run Code Online (Sandbox Code Playgroud)

你会看到元素的标签是'BODY'元素.如何使用javascript将焦点恢复到相同的元素,因为,这样的事情$('body').focus();不起作用.

编辑:它还应该重置文档的"焦点"流程.因此,单击TAB后,它将聚焦相同的元素,就像您要刷新页面然后单击TAB一样.

编辑2:我需要重点关注某些操作,如keyDown,重置为默认状态 - 加载页面后的状态.从我的研究中我知道,在你加载页面之后关注的元素是'body',然后在你点击Tab之后,你的网站焦点流中的第一个元素就会聚焦.我不能用$('body')来做那个.focus(); - 它不会聚焦身体,也不会重置文件焦点的当前流量.

编辑3:到目前为止我们已经设法以某种方式body使用此代码将焦点重置为网站元素:document.activeElement.blur();所以我的上述脚本会说body是重点,但它不会重置当前焦点的实际流量,当您使用键盘导航网站时(TAB按钮).可以使用解决方法并选择所需的指定元素,但这不是问题的答案.什么是将网站键盘导航流重置为默认状态而不刷新页面的通用机制?

编辑4: https ://jsfiddle.net/4qjb5asw/5/

Tyl*_*per 5

<body>您可以通过执行以下操作来清除活动元素的焦点,而不是专门聚焦 ,document.activeElement.blur();这应该将焦点恢复到<body>元素并重置焦点流。

单击下面的代码片段以查看当前情况document.activeElement

$("#reset").on("click", function() {
  document.activeElement.blur();
  logActiveElement();
});

$("form").children().on("focus", logActiveElement);

function logActiveElement() {
    console.log("The active element is now: " + $(document.activeElement).prop('tagName'));
}
Run Code Online (Sandbox Code Playgroud)
.blur {
  padding: 5px;
  border: 2px solid blue;
  margin-top: 20px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" />
  <textarea></textarea>
  <button type="button">Test Button</button>
</form>

<div class="blur">
  <button id="reset">RESET ACTIVE ELEMENT</button>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 它不会将焦点流重置为文档的默认值,请参阅:https://jsfiddle.net/4qjb5asw/5/ 移动,使用 TAB 到 Y 输入,然后单击 ESCAPE 按钮触发操作,然后单击 TAB - 它将移动到Z 输入,我希望它也重置焦点流,所以 X 输入应该聚焦。 (6认同)

Don*_*ong 0

这将使您指定的元素保持焦点

$(document).ready(function(){
    setInterval(function(){
     var focusbox = document.getElementById("element_to_focus");
     focusbox.focus();
    });
})
Run Code Online (Sandbox Code Playgroud)