【问题标题】:Scroll with arrow keys while text input is focused (Javascript)聚焦文本输入时使用箭头键滚动(Javascript)
【发布时间】:2013-12-10 09:12:57
【问题描述】:
我想在文本输入集中时使用箭头键滚动 HTML 页面。输入字段的焦点是使用以下代码创建的:
document.getElementById('search').focus();
我必须保持输入字段处于活动状态,因为我有一个可以写入该字段的条形码扫描仪。
是否可以使用 Javascript 来激活输入文本字段并允许同时使用箭头键滚动?
我在基于 Windows CE 6.0 的移动扫描仪上使用 IE 6。
【问题讨论】:
标签:
javascript
internet-explorer
scroll
keyboard
focus
【解决方案1】:
我不明白为什么不这样做 - 您可以简单地将事件处理程序添加到键并使用 jquery 滚动。
$(document).keydown(function(e){
if (e.keyCode == 40) {
// get current scroll
var scroll = $(window).scrollTop();
$(window).scrollTop(scroll+10);
return false;
} else if (e.keyCode == 38) {
// get current scroll
var scroll = $(window).scrollTop();
$(window).scrollTop(scroll-10);
return false;
}
});
在哪里
37 - left
38 - up
39 - right
40 - down
【解决方案2】:
有点棘手的问题,您必须禁用输入的自动完成功能:
<input id="search" autocomplete="off" />
然后绑定事件处理程序等:
document.onkeydown = function(event) {
// normalize event.which
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
if ( document.activeElement.id === 'search' ) { // #search has focus
if (event.which === 38) { // up arrow
window.scrollBy(0, -50);
}else if (event.which === 40) { // down arrow
window.scrollBy(0, 50);
}
}
}
document.getElementById('search').focus();
注意,当body有焦点时,箭头键默认滚动页面,所以要测试这个功能,你必须关注body以外的东西
FIDDLE