【发布时间】:2013-01-23 10:10:20
【问题描述】:
我编写了一些代码来限制我选择的某些元素的标签导航。您可以在此处查看完整的代码: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;
}
【问题讨论】:
-
我无法在 Chrome/linux 或 Firefox/linux 上重现您的问题:jsfiddle.net/7mfLb
-
你在什么浏览器上遇到问题?
-
Jquery 版本不同......在你的小提琴中你使用的是 1.9 在我的它是 1.72
-
所以...我建议更新你的 jQuery :)
-
我刚刚尝试过,但我不能因为与其他模块的所有依赖关系太复杂。我必须让它与这个版本一起工作
标签: jquery jquery-1.7