这是我刚写的一个实现。它更加复杂,因为它过滤了隐藏和禁用的输入,并处理具有相同标签索引的多个元素。目前只在Firefox中进行了测试。
咖啡:
getElementsInTabOrder = (form) ->
elements = Array.prototype.filter.call form.elements, (element) ->
return false if element.type is 'hidden'
return false if element.disabled
return true
elementsByTabIndex = []
for element in elements
tabIndex = element.tabIndex
unless elementsByTabIndex[tabIndex]?
elementsByTabIndex[tabIndex] = []
elementsByTabIndex[tabIndex].push element
return [].concat elementsByTabIndex...
getElementByDelta = (element, delta, wrap = true) ->
elements = getElementsInTabOrder element.form
length = elements.length
index = elements.indexOf element
targetIndex = index + delta
while targetIndex < 0
return null unless wrap
targetIndex += length
while targetIndex >= length - 1
return null unless wrap
targetIndex -= length
return elements[targetIndex]
getNextElement = (element, wrap = true) ->
return getElementByDelta element, 1, wrap
getPreviousElement = (element, wrap = true) ->
return getElementByDelta element, -1, wrap
module.exports = {
getElementsInTabOrder
getElementByDelta
getNextElement
getPreviousElement
}
Javascript:
var getElementByDelta, getElementsInTabOrder, getNextElement, getPreviousElement;
getElementsInTabOrder = function(form) {
var element, elements, elementsByTabIndex, i, len, ref, tabIndex;
elements = Array.prototype.filter.call(form.elements, function(element) {
if (element.type === 'hidden') {
return false;
}
if (element.disabled) {
return false;
}
return true;
});
elementsByTabIndex = [];
for (i = 0, len = elements.length; i < len; i++) {
element = elements[i];
tabIndex = element.tabIndex;
if (elementsByTabIndex[tabIndex] == null) {
elementsByTabIndex[tabIndex] = [];
}
elementsByTabIndex[tabIndex].push(element);
}
return (ref = []).concat.apply(ref, elementsByTabIndex);
};
getElementByDelta = function(element, delta, wrap) {
var elements, index, length, targetIndex;
if (wrap == null) {
wrap = true;
}
elements = getElementsInTabOrder(element.form);
length = elements.length;
index = elements.indexOf(element);
targetIndex = index + delta;
while (targetIndex < 0) {
if (!wrap) {
return null;
}
targetIndex += length;
}
while (targetIndex >= length - 1) {
if (!wrap) {
return null;
}
targetIndex -= length;
}
return elements[targetIndex];
};
getNextElement = function(element, wrap) {
if (wrap == null) {
wrap = true;
}
return getElementByDelta(element, 1, wrap);
};
getPreviousElement = function(element, wrap) {
if (wrap == null) {
wrap = true;
}
return getElementByDelta(element, -1, wrap);
};
module.exports = {
getElementsInTabOrder: getElementsInTabOrder,
getElementByDelta: getElementByDelta,
getNextElement: getNextElement,
getPreviousElement: getPreviousElement
};