如何使用箭头键在页面上的对象之间平滑地上下滚动? [英] How can one smooth scroll up and down between objects on a page with arrow keys?

查看:116
本文介绍了如何使用箭头键在页面上的对象之间平滑地上下滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个非常简单的网站,其中一系列图像垂直排列在页面上。我希望能够使用向上和向下箭头键平滑滚动从一个图像到下一个图像,向上或向下。这样,浏览所需的击键次数将被最小化,并且可以避免页面向下和向上翻页的无与伦比的间距。

I am building a very simple website with a series of images arranged vertically on a page. I would like to be able to use the up and down arrow keys to smooth scroll from one image to the next, up or down. This way the number of keystrokes required for browsing will be minimized and the unmatched spacing of page down and page up can be avoided.

我想这将是一个javascript函数。但是,我对使用javascript的经验不是很充实,所以我希望你能在答案中考虑一个初学者。现在,图像排列在一个 div 内,并用 br 分隔(多个换行符)。所以,我想可以在每个 img 中放置一个 id ,或者在每个<$周围放置识别标签c $ c> img 供javascript使用。或者,也许还有另一种方法可以使javascript识别通过箭头键滚动的步骤。做这个的最好方式是什么?谢谢。

I imagine that this is going to be a javascript function. However, I am not very experienced using javascript, so I hope you can consider a beginner in the answer. Right now, the images are arranged inside a single div and separated with br (multiple line breaks). So, I imagine it might be possible to place an id in each img or to place identifying tags around each img for the javascript to use. Or, perhaps, there is another way to make the javascript recognize the steps for scrolling via arrow keys. What is the best way to do this? Thank you.

推荐答案

如果您了解jQuery,这是一个有趣而简单的方法。按下向上/向下箭头键按下并阻止其默认滚动操作。然后根据箭头按下找到下一个或上一个图像。最后使用jQuery的animate将元素的顶部带入视图。当你超越列表末尾时,你需要进行一些错误检查,但我相信你可以根据这个来搞清楚。

This is a fun and easy one if you know jQuery. Catch the up/down arrow key presses and prevent their default scroll action. Then find the next or previous image based on the arrow press. Finally use jQuery's animate to bring the top of the element into view. You'll need to put in some error checking for when you go past the end of the list, but I am sure you can figure it out based on this.

< a href =http://jsfiddle.net/aVvQF/4/ =nofollow> http://jsfiddle.net/aVvQF/4/

$(window).keydown(function(e) {
    e.preventDefault(); //prevent default arrow key behavior

    var targetElement;
    //down
    if (e.keyCode == 40) {
        $targetElement = $('.active').next('img');
    }
    //up
    else if (e.keyCode == 38) {
        $targetElement = $('.active').prev('img');
    }
    if (!$targetElement.length) {return;}
    $('.active').removeClass('active');
    $targetElement.addClass('active');

    //scroll element into view    
    $('html, body').clearQueue().animate({scrollTop: $targetElement.offset().top }, 1000);
});

这篇关于如何使用箭头键在页面上的对象之间平滑地上下滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆