I have a small photography portfolio site that I use to share pictures with my relatives. The photos are laid out every 1000px or so in a vertical scrolling page. An example is here: http://pavelrozman.com/photo/events/jamison/ . Right now I have a small Javascript that lets you scroll 800px with the arrow keys. This is okay, but it's inconsistent because of varying image heights. I read an article on The Verge, and it has exactly what I'm looking for but I have no idea how to implement it because I know nothing about Javascript/jQuery. The article is here http://www.theverge.com/2013/7/29/4560214/point-and-shoot-perfection-an-evening-with-sonys-rx100m2 and I'd like to copy the "Use 'd' and 's' to scroll" feature where it scrolls to the top of the next or previous image, but use the arrow keys instead of 's' and 'd' if possible. Thanks in advanced.

有帮助吗?

解决方案

Off the top of my head, make a list of the top offsets of each image, and then when pressing the down/up arrows, compare the scrollTop position to the image positions to determine which one is closest in the up/down direction.

var locs = [];

// Save offsets of each image
// Use a better selector in real life
$('img').each(function () {
    locs.push($(this).offset().top);
});

$(document).keydown(function (e) {

    switch (e.which) {
        case 37:
        case 38:
        case 83:
            // Get the current scroll position 
            var sTop = parseInt($(document).scrollTop());

            // For UP, go through the list backward until
            // you find one before the current scroll position
            for (i = locs.length-1; i >= 0; i--) {
                if (locs[i] < sTop) {
                    $(document).scrollTop(locs[i]);
                    break;
                }
            }
            break;
        case 39:
        case 40:
        case 68:
            // Get the current scroll position 
            var sTop = parseInt($(document).scrollTop());

            // For DOWN, go through the list until
            // you find one after the current scroll position
            for (i = 0; i < locs.length; i++) {
                if (locs[i] > sTop + 1) {
                    $(document).scrollTop(locs[i]);
                    break;
                }
            }
            break;
        default:
            return true;
    }

    return false;
});

Demo: http://jsfiddle.net/9BEbh/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top