我尝试定期更改元素子元素的焦点。这个EXAMPLE
<div id="test">
<p>This is a test</p>
<p>another test</p>
<p>Thirs test</p>
</div>
和CSS
#test p {
color:blue
}
#test p:active, #test p:focus {
color:red;
}
和 JavaScript
function test() {
var el = document.getElementById("test"),
nodes = el.getElementsByTagName("p"),
j = nodes.length - 1,i=0;
var id = setInterval(
function () {
nodes[i].focus();
if (i == j) {
i = 0;
} else {
i++;
}
}, 1000);
};
test();
但是这个简单的例子不起作用。该问题与 nodes[i].focus();
相关,因为 nodes[i].style.color='red';
有效。
我知道这种方法并不完美,我感谢任何改进事件的评论。
最佳答案
问题是默认情况下段落是不可聚焦的,事件状态是通过单击触发的,但不是焦点事件。要使其正常工作,您只需使这些段落可聚焦:
<div id="test">
<p tabindex=0>This is a test</p>
<p tabindex=0>another test</p>
<p tabindex=0>Thirs test</p>
然后您可能想在某个时刻清除间隔,或者更好的是,使用 setTimeout
(除非您希望它永远运行......)但这是一个不同的问题。这是一个演示,其中包含您的确切代码,但具有可聚焦的 p
:
关于javascript - 在 setInterval 中使用 focus(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18951916/