Prevent default behavior in text input while pressing arrow up(按向上箭头时防止文本输入中的默认行为)
问题描述
我正在使用带有数值的基本 HTML <input type="text"/> 文本字段.
I’m working with basic HTML <input type="text"/> text field with a numeric value.
我正在添加 JavaScript 事件 keyup 以查看用户何时按下向上箭头键 (e.which == 38) - 然后我增加数值.
I’m adding JavaScript event keyup to see when user presses arrow up key (e.which == 38) – then I increment the numeric value.
代码运行良好,但有一件事让我很头疼.当我按向上箭头键时,Safari/Mac 和 Firefox/Mac 都会在最开始移动光标.据我所知,这是每个 <input type="text"/> 文本字段的默认行为,这是有道理的.
The code works well, but there’s one thing that bugs me. Both Safari/Mac and Firefox/Mac move cursor at the very beginning when I’m pressing the arrow up key. This is a default behavior for every <input type="text"/> text field as far as I know and it makes sense.
但这不会产生光标前后跳动的非常美观的效果(在更改值之后).
But this creates not a very aesthetic effect of cursor jumping back and forward (after value was altered).
一开始的跳转发生在 keydown 上,但即使有了这些知识,我也无法阻止它发生.我尝试了以下方法:
The jump at the beginning happens on keydown but even with this knowledge I’m not able to prevent it from occuring. I tried the following:
input.addEventListener('keydown', function(e) {
e.preventDefault();
}, false);
将 e.preventDefault() 放入 keyup 事件也无济于事.
Putting e.preventDefault() in keyup event doesn’t help either.
有什么办法可以防止光标移动吗?
Is there any way to prevent cursor from moving?
推荐答案
要保留光标位置,请在更改值之前备份 input.selectionStart.
To preserve cursor position, backup input.selectionStart before changing value.
问题在于 WebKit 对 keydown 做出反应,而 Opera 更喜欢 keypress,因此存在问题:两者都被处理和限制.
The problem is that WebKit reacts to keydown and Opera prefers keypress, so there's kludge: both are handled and throttled.
var ignoreKey = false;
var handler = function(e)
{
if (ignoreKey)
{
e.preventDefault();
return;
}
if (e.keyCode == 38 || e.keyCode == 40)
{
var pos = this.selectionStart;
this.value = (e.keyCode == 38?1:-1)+parseInt(this.value,10);
this.selectionStart = pos; this.selectionEnd = pos;
ignoreKey = true; setTimeout(function(){ignoreKey=false},1);
e.preventDefault();
}
};
input.addEventListener('keydown',handler,false);
input.addEventListener('keypress',handler,false);
这篇关于按向上箭头时防止文本输入中的默认行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按向上箭头时防止文本输入中的默认行为
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
