防止空格和箭头键滚动网页?

时间:2014-12-23 20:06:55

标签: javascript

当元素被聚焦以在网页上提供键盘支持时,我会覆盖空格键和箭头键的行为。我需要禁用这些键的默认行为,即滚动网页。我认为做到这一点所需要的只是return false当你处理事件时,但那并没有做到这一点。我还添加了preventDefault,但除了执行自定义操作外,它还会滚动页面。这有什么问题?

document.getElementById('someID').onkeyup = function(e) {
    var keyCode = e.which || e.keyCode;
    var handled = false;

    if (keyCode == 38 || keyCode == 40) { //up or down arrow
        //do something fun
        e.preventDefault();
        handled = true;
    }

    return !handled; //return false if the event was handled
}

1 个答案:

答案 0 :(得分:3)

将活动更改为onkeydown。当你到达onkeyup时已经太晚了,滚动已经改变了。

document.getElementById('someID').onkeydown = function(e) {
    var keyCode = e.which || e.keyCode;
    var handled = false;

    if (keyCode == 38 || keyCode == 40) { //up or down arrow
        //do something fun
        e.preventDefault();
        handled = true;
    }

    return !handled; //return false if the event was handled
}