javascript控制键盘right键在input中将光标右移
发布网友
发布时间:2022-04-20 09:22
我来回答
共2个回答
热心网友
时间:2022-04-25 06:48
onkeydown事件里面写
如下,我简单写了一下:
<html>
<head>
<script type="text/javascript">
function whichButton(obj, event) {
var keycode = event.which || event.keyCode;
//按下了right键
if (keycode == 39) {
//如果光标的位置到了6,则按键不生效
if (getCursorPosition(obj) >= 6) {
return false;
}
}
}
//判断光标的索引
function getCursorPosition(obj) {
var cursurPosition = -1;
if (obj.selectionStart) {
cursurPosition = obj.selectionStart;
} else {
var range = document.selection.createRange();
range.moveStart("character", -obj.value.length);
cursurPosition = range.text.length;
}
return cursurPosition;
}
</script>
</head>
<body>
<input type='text' value='123456abcd' onkeydown="return whichButton(this,event)">
</body>
</html>
热心网友
时间:2022-04-25 08:06
在js中这么写
var num = 0;
input.onkeyup = function (e) {
e = e || window.event;
if (e.which === 39 && num ++ >= 5) {
return false;
}
}