如果每个元素都有自己的tabindex
,如下所示:
<a href="http://example.com" tabindex="3">Link</a>
<input type="text" tabindex="2">
<select tabindex="5">
<option>Option A</option>
<option>Option B</option>
<option>Option C</option>
</select>
<textarea tabindex="4">Hello world</textarea>
<button tabindex="1" id="Btn">Button</button>
现在,我向 button[id=Btn]
附加一个事件,该事件将所有元素的 tabindex
设置为 -1
,如下所示:
document.getElementById("Btn").addEventListener("click", function(){
var allElement = document.querySelectorAll("a,area,button,input,object,select,textarea");
for(var i = 0; i < allElement.length; i++){
allElement[i].setAttribute("tabindex",-1);
}
});
点击button[id=Btn]
后,如何将所有元素重置为其原始tabindex
?
最佳答案
将当前的tabindex
保存在data-
属性中,并在需要时使用它来恢复原始的tabindex值:
var allElement = document.querySelectorAll("a,area,button,input,object,select,textarea");
document.getElementById("Btn").addEventListener("click", function() {
for (var i = 0; i < allElement.length; i++) {
allElement[i].setAttribute("data-tabindex", allElement[i].getAttribute("tabindex"));
allElement[i].setAttribute("tabindex", -1);
}
});
document.getElementById("BtnRes").addEventListener("click", function() {
for (var i = 0; i < allElement.length; i++) {
allElement[i].setAttribute("tabindex", allElement[i].getAttribute("data-tabindex"));
allElement[i].removeAttribute("data-tabindex", -1);
}
});
<a href="http://example.com" tabindex="3">Link</a>
<input type="text" tabindex="2">
<select tabindex="5">
<option>Option A</option>
<option>Option B</option>
<option>Option C</option>
</select>
<textarea tabindex="4">Hello world</textarea>
<button tabindex="1" id="Btn">Button</button>
<button tabindex="1" id="BtnRes">restore tabindex</button>
关于javascript - 如何临时设置所有元素的 tabindex 属性并能够将所有元素重置为其原始 tabindex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48262580/