당신은 함께
previousSibling
및
nextSibling
특성, 이전 및 다음 요소 형제 (있는 경우)로 이전 및 다음 DOM 형제 (있는 경우)에 액세스 할 수 있습니다
previousElementSibling
및 nextElementSibling
속성 사이를 이동하려는 요소가 모두 다른 형제가 아닌 경우 이는 더욱 까다로워집니다. JS 라이브러리는 탐색을 단순화하는 큰 도움이 될 것입니다. tabIndex
위해 입력 콜렉션을 생성하고, 사용자가 해당 키하거나, 입력 게인을 누르거나 포커스를 잃을 때마다 갱신하는 현재 입력 트랙을 지키는 elements
속성을 사용
또한 수 전처리 형태.
DOM 기반의 접근 방식 (안된, 가능 아마 버그) :
이
if (! Array.prototype.append) {
Array.prototype.append = function(arr) {
this.push.apply(this, arr);
}
}
if (! Array.prototype.each) {
Array.prototype.each = function(f) {
for (var i=0; i < this.length; ++i) {
f(this[i], i);
}
}
}
if (! Array.prototype.filter) {
Array.prototype.filter = function(f) {
var other = [];
if (!f) {
f = function (x) {return x;};
}
for (var i=0; i < this.length; ++i) {
if (f(this[i])) {
other.push(this[i]);
}
}
return other;
}
}
// call this on the form element
function keyNavigation(form, nextKey, prevKey, modifier) {
if (nextKey) {
nextKey = nextKey.toLowerCase();
} else {
nextKey = 'n';
}
if (prevKey) {
prevKey = prevKey.toLowerCase();
} else {
prevKey = 'p';
}
switch (modifier) {
case 'ctrlKey':
case 'altKey':
case 'metaKey':
break;
case 'ctrl':
case 'alt':
case 'meta':
modifier += 'Key';
break;
default:
modifier = 'ctrlKey';
break;
}
var inputs=[], assigned = [], unassigned=[], input, j=0;
for (var i=0; i < form.elements.length; ++i) {
input = form.elements[i];
if (input.tabIndex) {
j = input.tabIndex;
while(assigned[j]) {++j}
assigned[j] = input;
} else if (!input.disabled) {
unassigned.push(input);
}
}
inputs = assigned.filter();
inputs.append(unassigned);
inputs.each(function (input, keyedIdx) {
input.keyedIdx = keyedIdx;
});
var currIdx;
form.gotoNextInput = function() {
// if currIdx is undefined, comparison should be false
if (currIdx+1 < inputs.length) {
inputs[++currIdx].focus();
}
}
form.gotoPreviousInput = function() {
// if currIdx is undefined, comparison should be false
if (currIdx && currIdx > 0) {
inputs[++currIdx].focus();
}
}
form.addEventListener('keypress', function (evt) {
if (evt[modifier]) {
switch (String.fromCharCode(evt.keyCode).toLowerCase()) {
case nextKey:
evt.stopPropagation();
evt.preventDefault();
this.gotoNextInput();
return false;
case prevKey:
evt.stopPropagation();
evt.preventDefault();
this.gotoPreviousInput();
return false;
}
}
}, true);
// programmatic setting of focus above should invoke this
// handler. Wasteful, but not problematic.
form.addEventListener('focus', function (evt) {
if (typeof evt.target.keyedIdx == 'number') {
currIdx = evt.target.keyedIdx;
}
}, true);
form.addEventListener('blur', function (evt) {
delete currIdx;
}, true);
}
: -/"N"및 "P"키없이 텍스트를 어떻게 입력 하시겠습니까? –
다음 * HTML 요소 *가 다음 * 입력 요소 *와 다릅니다. 원하는게 뭐야? –
@Felix Kling, @Aaron Digulla 샘플 코드로 질문을 업데이트했습니다.Text Box, Button 또는 Image – Simsons