是否有一种方法可以通过编程触发TAB键将焦点移动到下一个可聚焦的元素

Is there a way to programmatically trigger the TAB key to move the focus to the next focusable element?

本文关键字:移动 焦点 下一个 元素 聚焦 TAB 一种 编程 可以通过 方法 是否      更新时间:2023-09-26

我正在编写一个单元测试来测试我的网页上的选项卡顺序,我找不到一种方法来模拟用户按下tab键以专注于下一个可聚焦的元素,尽管这似乎是一项简单的任务。

允许使用jQuery,但优先使用纯javascript解决方案。如有任何帮助,不胜感激。

// TODO
function triggerTab () {
}
$("#btn-save").focus();
triggerTab();
// Expect the focus is on the cancel button now.
console.log(document.activeElement.id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> some text </p> 
<button id="btn-save"> save </button>
<button id="btn-cancel> cancel </button>

注:对下一个可聚焦的元素调用focus()是不可接受的,即使您可以编写代码来找出下一个可聚焦的元素。所以这个路径不是我想要的:

function getAllFocusables () {
    ...
}
var focusables = getAllFocusables(),
    index = focusables.indexOf(document.activeElement);
$(focusables[index+1]).focus();

你不能使用Javascript模拟标准浏览器中的选项卡键。

如果您正在使用无头浏览器进行单元测试,例如phantomjs您可以模拟制表键

var webPage = require('webpage');
var page = webPage.create();
page.sendEvent('keypress', page.event.key.Tab);