只覆盖箭头键滚动事件

override just the arrowkey scroll event

本文关键字:滚动 事件 覆盖      更新时间:2023-09-26

所以我正在创建一个自定义滚动框,因为标准的html<select>框没有剪切它(我需要显示两列,但找不到如何使用<select>)。无论如何,我有一个可滚动的表,它正按照我想要的方式工作。除了上下箭头键触发整体滚动,而不是选择表中的前一个或前一个元素。

html<使用适当的上下绑定选择>http://jsfiddle.net/a5YJK/

我的自定义选择没有适当的上下http://jsfiddle.net/8zgxA/3/

当我运行时

$('#wrap *').scroll(function(e){}); 

我无法区分鼠标滚动和向上或向下箭头。如何区分?

只需检查滚动事件中不存在的e.keyCodee.which

$(window).on('keyup scroll', function(e){
    console.log(e.keyCode); //undefined for mouse scroll
    if(e.keyCode && e.keyCode == 40){
        //down arrow, scroll might occur, so prevent it or do whatever
    }
}); ​

演示

<table onfocus="focused(1)" onblur="focused(0)" onkeypress="selectnext(event)">
.
.
.
</table>
<script type="text/javascript">
var currentrow = 0;
var tablefocused;
function focused(a)
{
switch(a)
{
case 1:
tablefocused = 1;
break;
case 0:
tablefocused = 0;
break;
}
}
function selectnext(e)
e.stopPropagation();
{
if(tablefocused==1)
{
switch(e.keyCode)
{
case 38:
currentrow = currentrow-1;
this.childNodes[currentrow].style.backgroundColor = "blue";
$('tr').css('background', '');
break;
case 40:
currentrow = currentrow+1;
this.childNodes[currentrow].style.backgroundColor = "blue";
$('tr').css('background', '');
break;
}
}
}
</script>

我在这段代码中遗漏了一些细节,例如"currentrow"不应该转到-1,单击一行应该将currentrow的值更改为该行,例如

哦,为了防止滚动,您可以使用stopPropagation()函数来防止事件冒泡。