我编写了一些代码来限制我选择的某些元素的选项卡导航。您可以在这里看到完整的代码:http: //jsfiddle.net/M2ELL/2/它工作正常。
问题是我想“装饰”焦点所在的父 div。为此,我制作了这些事件监听器:
$('[data-mymodaltabindex]').blur(function () {
$(this).parent().removeClass('highlight');
console.log('blur ' + $(this));
});
$('[data-mymodaltabindex]').focus(function () {
$(this).parent().addClass('highlight');
console.log('highlight ' + $(this));
});
当每个父 div 只有一个输入时,这些会按预期工作。另一方面,当每个父 div 有两个输入时(如我的示例中的两个收音机),焦点事件总是发生在模糊事件之前。结果是突出显示然后删除 div 上的突出显示,这与我想要的相反。
我希望模糊事件发生在导致删除突出显示然后突出显示之前。我怎样才能做到这一点?为什么在这种情况下焦点事件总是发生在模糊事件之前?
完整代码:
<div>
radio 1
<input type="radio" data-mymodaltabindex="1" />
radio 2
<input type="radio" data-mymodaltabindex="2" />
</div>
<div>
text
<input type="text" data-mymodaltabindex="3" />
</div>
$('[data-mymodaltabindex]').on('keydown', function (e) {
if (e.keyCode == 9 || e.which == 9) {
// define variables
var mytabindex = null;
var maximum = null;
var minimum = null;
var next = null;
var previous = null;
var values = new Array();
// set mytabindex on the actual focused control
var mytabindex = $(this).attr('data-mymodaltabindex');
// put every visible mytabindex into array
$('[data-mymodaltabindex]:visible').each(function () {
values.push(parseInt($(this).attr('data-mymodaltabindex')));
});
//console.log(values);
// look for maximum minimum mytabindex
// for maximum and minimum we filter out null values
// as they are interpreted as 0 with math functions
maximum = Math.max.apply(null, values.filter(function (val) { return val !== null }));
minimum = Math.min.apply(null, values.filter(function (val) { return val !== null }));
// set next and previous using function
next = getModalClosestHighValue(values, mytabindex);
previous = getModalClosestLowValue(values, mytabindex);
// go back to begining / end if
// end / begining is reached
if (!previous) { previous = maximum; }
if (!next) { next = minimum; }
// check if there is shift combination
if (e.shiftKey) {
mytabindex = previous; // focus on the previous item
} else {
mytabindex = next; // focus on the next item
}
// focus on this element
$('[data-mymodaltabindex=' + mytabindex + ']').focus();
console.log('focus set to [data-mymodaltabindex=' + mytabindex + ']');
// stop propagation
return false;
}
});
function getModalClosestHighValue(a, x) {
var hi;
for (var i = a.length; i--; ) {
if (a[i] > x && (hi === undefined || hi > a[i])) hi = a[i];
};
return hi;
}
function getModalClosestLowValue(a, x) {
var lo;
for (var i = a.length; i--; ) {
if (a[i] < x && (lo === undefined || lo < a[i])) lo = a[i];
};
return lo;
}