有没有办法以编程方式触发 TAB 键将焦点移动到下一个可聚焦元素? [英] Is there a way to programmatically trigger the TAB key to move the focus to the next focusable element?

查看:40
本文介绍了有没有办法以编程方式触发 TAB 键将焦点移动到下一个可聚焦元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a unit test to test the tab order on my webpage and I could not find a way to simulate the user's keying down of the TAB key to focus on the next focusable element, though this seems to be an easy task.

jQuery 是允许的,而纯 javascript 解决方案是首选.任何形式的帮助表示赞赏.

jQuery is allowed while pure javascript solution is preferred. Any kind of help is appreciated.

// 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() 是不可接受的,即使您可以编写代码来找出下一个可聚焦元素.所以这条路不是我想要的:

P.S. It is no acceptable to call focus() on the next focusable element, even if you can write code to figure out the next focusable element. So this path is NOT what I want:

function getAllFocusables () {
    ...
}

var focusables = getAllFocusables(),
    index = focusables.indexOf(document.activeElement);

$(focusables[index+1]).focus();

推荐答案

您无法使用 Javascript 从标准浏览器模拟 Tab 键.

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

If you are doing your unit test using a headless browser, like phantomjs for instance, you can emulate the tab key

var webPage = require('webpage');
var page = webPage.create();

page.sendEvent('keypress', page.event.key.Tab);

这篇关于有没有办法以编程方式触发 TAB 键将焦点移动到下一个可聚焦元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆