最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop window scroll with keycode (arrows), event.preventDefault() not working? - Stack Overflow

programmeradmin4浏览0评论

I built an autosuggest, and keycode works to navigate up and down through the list, but it scrolls the window. I have tried event.preventDefault() but it is not stopping it. Any ideas? This is what I have tried:

$(document).keyup(function(e) {
e.returnValue=false;
e.preventDefault();
switch(e.keyCode) {
    case 40:
        suggestionLine++;
                $('#suggestionLine_'+suggestionLine).focus();
                break;
// etc...

Thank you!

I built an autosuggest, and keycode works to navigate up and down through the list, but it scrolls the window. I have tried event.preventDefault() but it is not stopping it. Any ideas? This is what I have tried:

$(document).keyup(function(e) {
e.returnValue=false;
e.preventDefault();
switch(e.keyCode) {
    case 40:
        suggestionLine++;
                $('#suggestionLine_'+suggestionLine).focus();
                break;
// etc...

Thank you!

Share Improve this question edited Jan 30, 2013 at 19:50 Ben Kirchner asked Jan 30, 2013 at 19:01 Ben KirchnerBen Kirchner 3033 silver badges9 bronze badges 4
  • 1 tried return false instead of e.returnValue=false;? – Suresh Atta Commented Jan 30, 2013 at 19:02
  • like @TheSureshAtta at the bottom of your function put return false; instead of your e.returnValue = false; – Ryan Commented Jan 30, 2013 at 19:10
  • you need both e.preventDefault(); and e.stopPropagation(); – geniuscarrier Commented Jan 30, 2013 at 19:37
  • I tried return false, and e.stopPropagation(); still scrolling! I've looked all over the web. I'm out of ideas! – Ben Kirchner Commented Jan 30, 2013 at 19:47
Add a ment  | 

1 Answer 1

Reset to default 12

You need keydown, not keyup.

Why? The default operation that you're trying to prevent happens immediately when you press the key (try it now!). This allows for things like autorepeat, which will send multiple keydown events before sending a single keyup event. By the time keyup is fired, the scrolling has already taken place.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论