How to scroll page elements with the keyboard?

2019-02-15 13:17发布

I basically want to achieve the same effect as in Google Reader: when you press "j", you are pushed down to the next article and when you press "k", you can go back up to the previous article. What is the simplest way of doing this?

3条回答
Deceive 欺骗
2楼-- · 2019-02-15 13:48

Using onkeyup and use the keyCode to determine the key pressed: http://jsfiddle.net/pimvdb/gzRwN/1/.

document.body.onkeyup = function(e) {
    var code = e.keyCode;
    if(code === 74) { // key code for j
        window.scrollTo(document.body.scrollLeft,
                        document.body.scrollTop + 500);
    }
};
查看更多
Bombasti
3楼-- · 2019-02-15 13:58

Get the number/value for those keys and bind them to the event that you'd like them to execute. Much in the way that a click would be used to fire a function, but instead you're using a certain key.

查看更多
地球回转人心会变
4楼-- · 2019-02-15 14:05

https://github.com/jeresig/jquery.hotkeys

jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination.

查看更多
登录 后发表回答