請問有辦法把底下的JS改成在chrome按方向鍵向右時自動觸發TAB嗎?
case "ArrowRight": //右向鍵
var tIndex;
if (obj.value == "借" || obj.value == "貸" || obj.value == "選貼摘要") {
event.key = "Tab"; //Tab鍵
}
else {
if (obj.createTextRange) { //for IE
var r = document.selection.createRange().duplicate();
r.moveEnd('character', obj.value.length)
tIndex = obj.value.lastIndexOf(r.text)
}
else { //for Firefox
tIndex = obj.selectionStart;
}
if (obj.value.length == tIndex)
event.key = "Tab";
}
break;
修正後
case 39:
if (obj.tagName.toLowerCase() === 'input' && obj.type === 'text') {
event.preventDefault();
const inputs = Array.from(document.querySelectorAll('input[type="text"]'));
const elementsWithTabIndex = inputs.filter(function (element) {
return element.getAttribute('tabindex') !== '-1';
});
const targetIndex = elementsWithTabIndex.indexOf(obj);
if (targetIndex === elementsWithTabIndex.length - 1) {
elementsWithTabIndex[0].focus();
} else {
elementsWithTabIndex[targetIndex + 1].focus();
}
}
break;
case "ArrowRight": //右向鍵
var tIndex;
if (obj.value == "借" || obj.value == "貸" || obj.value == "選貼摘要") {
event.key = "Tab"; //Tab鍵
}
else {
if (obj.createTextRange) { //for IE
var r = document.selection.createRange().duplicate();
r.moveEnd('character', obj.value.length)
tIndex = obj.value.lastIndexOf(r.text)
}
else { //for Firefox
tIndex = obj.selectionStart;
}
if (obj.value.length == tIndex) {
event.preventDefault(); //取消原本方向鍵的預設行為
var e = new KeyboardEvent("keydown", {
bubbles: true,
cancelable: true,
keyCode: 9 //Tab鍵的keyCode
});
obj.dispatchEvent(e); //觸發Tab鍵事件
}
}
break;