防止箭头键更改选定的单选按钮 [英] Prevent arrow keys from changing selected radio button
问题描述
我有几个单选按钮,但我想防止按下向上/向下箭头键来更改所选的单选按钮.
I've got a couple of radio buttons and I would like to prevent the pressing of the up/down arrow keys to change the selected radio button.
如果选择一个单选按钮,然后按向上/向下箭头键,它将选择上一个或下一个单选按钮.相反,我希望选择保持不变.为此,我可以在某些按键上使用event.preventDefault();
.但是,我仍然希望用户能够通过按箭头键在页面上上下滚动.
If you select one of the radio buttons and then press the up/down arrow key it will select the previous or next radio button. Instead I want the selection to remain unchanged. For this I could just use event.preventDefault();
on certain key presses. However I still want the user to be able to scroll up and down on the page by pressing the arrow keys.
我该怎么做?
单选按钮:
<label>Value
<input type="radio" name="myradiobtn" value="value1">
</label>
<label>Value
<input type="radio" name="myradiobtn" value="value2">
</label>
<label>Value
<input type="radio" name="myradiobtn" value="value3">
</label>
<label>Value
<input type="radio" name="myradiobtn" value="value4">
</label>
<label>Value
<input type="radio" name="myradiobtn" value="value5">
</label>
JavaScript尝试(不起作用):
Javascript attempt (not working):
$(document).keydown(function(e) {
var arrowKeys = [37,38,39,40];
if (arrowKeys.indexOf(e.which) !== -1) {
$('input[type="radio"]').each(function( index ) {
$(this).blur();
});
}
});
JsFiddle:
推荐答案
该想法是从input
移除焦点并防止input
keydown
事件处理程序中的默认行为:
The idea is to remove focus from input
and to prevent default behaviour in input
keydown
event handler:
小提琴.
$('input[type="radio"]').keydown(function(e)
{
var arrowKeys = [37, 38, 39, 40];
if (arrowKeys.indexOf(e.which) !== -1)
{
$(this).blur();
return false;
}
});
由@ user3346601解决,因为它未在第一个keydown
上滚动:
Mentioned by @user3346601 workaround for not scrolling on first keydown
:
小提琴.
$('input[type="radio"]').keydown(function(e)
{
var arrowKeys = [37, 38, 39, 40];
if (arrowKeys.indexOf(e.which) !== -1)
{
$(this).blur();
if (e.which == 38)
{
var y = $(window).scrollTop();
$(window).scrollTop(y - 10);
}
else if (e.which == 40)
{
var y = $(window).scrollTop();
$(window).scrollTop(y + 10);
}
return false;
}
});
这篇关于防止箭头键更改选定的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!