更新
警告:Chrome(错误)行为在不同平台上有所不同!在 Chrome Windows 中,在释放选择后立即触发 keydown 事件,而在 OsX 中则不会。这就解释了为什么 @judgeja 解决方案对某些人有效,而对我无效,而我的解决方案在 OsX 上工作而不是在 Windows 上。
所以我创建了一个更新的小提琴来将我的 OsX 解决方案与他的 Windows 解决方案合并。
http://jsfiddle.net/0fz5vcq6/5/
在触发 keydown 的平台上使用@judgeja 解决方案,如果没有触发它,它会在没有之前的 keydown 的情况下测试 keyup 事件(我之前的解决方案)。它很丑,因为它仅在释放 shift 键后才有效,但仅在 Chrome OsX 上很丑。
var shifted = false;
var hackytimer = 0;
var lastval=null;
$(document).keydown(function(e){
if(e.which == 16){
if(Date.now() - hackytimer <200){
alert("you pressed shift inside the select (Win)");
changeAllSelects($(this).val());
} shifted = true;
}
});
$(document).keyup(function(e){
if(e.which == 16) {
if(!shifted && lastval!=null) {
alert("you pressed shift inside the select (OsX)");
$('.report_info select').each(function () {
changeAllSelects(lastval);
});
}
shifted = false;
}
});
$(document).on('change', '.report_info select', function (e) {
hackytimer = Date.now();
if (shifted) {
changeAllSelects($(this).val());
} else {
lastval=$(this).val();
}
});
function changeAllSelects(cr){
hackytimer = 0;
$('.report_info select').each(function () {
$(this).val(cr);
});
}
这主要归功于 @judgeja 的计时器解决方案,并为 Mac(和其他行为相同的平台)添加了一些解决方法
我仍然认为使用像 http://gregfranko.com/jquery.selectBoxIt.js/ 这样的 HTML 来模拟选择更干净,因为它们不应该干扰 keydown/keyups。
以前的解决方案(仅限 OsX)
在完全没有任何事件的情况下,我能想到的唯一解决方案是测试在没有上一次降档的情况下是否发生了升档。如果您没有其他与选择行为方式相同的元素,这可能会起作用
http://jsfiddle.net/6jkkgx5e/
这有点棘手和肮脏,在用户释放 shift 键后才能工作
var shifted = false;
var lastval=null;
$(document).keydown(function(e){
if(e.which == 16){
shifted = true;
}
});
$(document).keyup(function(e){
if(e.which == 16){
if(!shifted && lastval!=null) {
alert("you pressed shift inside the select");
$('.report_info select').each(function () {
$(this).val(lastval);
});
}
shifted = false;
}
});
$(document).on('change', '.report_info select', function (e) {
var cr = $(this).val();
if (shifted) {
$('.report_info select').each(function () {
$(this).val(cr);
});
} else {
lastval=cr;
}
});
应该在没有问题的浏览器上正常运行。无论如何,我同意使用像http://gregfranko.com/jquery.selectBoxIt.js/ 这样的 HTML 来模拟选择可能是更简洁的方式。