[英]Iterate through children with tabulator (HTML)
让我们来一段这样的代码:
<article>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
</article>
我想使用tab
键<p>
这些<p>
-s进行迭代,并用CSS(轮廓线或其他标记)标记当前选择的<p>
。 我试图将tabindex
添加到<p>
-s,但似乎不起作用。
我的问题是:
<article>
内部? 我希望迭代跳到最后一个之后的第一个<p>
,反之亦然。 纯粹的HTML / CSS解决方案会更好,但是我对JS也很好。
使用tabindex="0"
来设置p
而在CSS :focus
使用background:red;
width:fit-content;
使background
仅适合内部text
也使用 onmousedown="return false;"
防止鼠标单击focus
p:focus{ background:red; width:fit-content; }
<article> <p onmousedown="return false;" tabindex="0">some text</p> <p onmousedown="return false;" tabindex="0">some text</p> <p onmousedown="return false;" tabindex="0">some text</p> <p onmousedown="return false;" tabindex="0">some text</p> <p onmousedown="return false;" tabindex="0">some text</p> </article>
是否有可能以这种方式迭代非输入/链接元素?
是的,使用tabindex
可以很好地解决此问题。
如果可能,捕获当前元素的伪类是什么?
是的,您可以将CSS :focus
规则用于大纲:
p:focus { border: 1px solid #ddd; }
<article> <p tabindex="0">some text</p> <p tabindex="0">some text</p> <p tabindex="0">some text</p> <p tabindex="0">some text</p> <p tabindex="0">some text</p> </article> This input isn't in the tab order: <input type="text" tabindex="-1">
( tabindex="0"
根据元素在文档顺序中的位置将其按Tab键顺序放置。当然,也可以按自己的顺序分配它们。)
如果默认情况下您具有按Tab键顺序排列的元素,并且不希望它们按Tab键顺序排列,则可以使用tabindex="-1"
将其从其中删除。 但是,出于可访问性原因,我不建议这样做。 上面的input
证明了这一点。
奖励:是否可以将迭代保留在内部? 我希望迭代跳到第一个
最后一次之后,反之亦然。
我认为您不能以这种方式来确定范围,而不必将这些设为页面上唯一可选项卡的元素,或者在离开最后一个并明确集中第一个元素时使用JavaScript来捕获它怀疑会导致UX问题)。
选择文章中的所有p。 将其tabIndex设置为0。然后在窗口上添加一个事件侦听器。 如果您文章中的最后一个p被关注,则下一个关注的元素将是p列表中的第一个元素。
const ps = document.querySelectorAll('article > p'); ps.forEach((p)=>p.tabIndex=0); ps[0].focus(); window.addEventListener("keydown", function(e){ const code = e.keyCode; if(code === 9 && ps[ps.length-1] === document.activeElement){ ps[0].focus(); e.preventDefault(); } }, false);
p:focus { border: 1px solid black; }
<article> <p>some text</p> <p>some text</p> <p>some text</p> <p>some text</p> <p>some text</p> </article>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.