Jquery箭头键导航

时间:2014-12-06 00:46:05

标签: jquery html css

我是jquery编程的新手。我想要做的是让页面向下滚动到下一个"容器"我每次按下箭头,然后用向上箭头反转。我已经尝试过谷歌搜索,但我似乎无法找到一个可管理的解决方案。

这是我的HTML代码:

<div class="containers">
    <div class="boxed" class="container">
        <p class="overskrift1">Internet Kriminalitet</p>
        <div id="demo"></div>
    </div>
    <div class="boxed2" class="container">

    </div>
</div>

我希望箭头键在不同容器之间导航。

修改

这可能是我迄今为止最好的jquery代码:

$('body').on('keypress'), (function () {
var ele = $(this).closest("section").find(".container");
$("body").animate({
scrollTop: $(ele).offset().top
                }, 100);
return false;

});

谢谢

  • 的Morten

2 个答案:

答案 0 :(得分:3)

你要做的是:

  • 在听取keypress

  • 的正文上放置一个事件
  • 切换键以获取按下的箭头。 (37,38,39,40 =&gt;左,上,右下)。

  • 按下该键时,您必须将页面scrollTop设置为元素顶部的动画。

类似的东西:

var containers = $('.container');
var currentContainer = containers.get(0);
$('body').on('keydown', function (e) {
    e.preventDefault();
    console.log(e.which);
    switch (e.which) {
        case 37:
            // left
            break;

        case 38:
            // up
            currentContainer = currentContainer.prev();
            break;

        case 39:
            // right
            break;

        case 40:
            // down
            currentContainer = currentContainer.next();
            break;

        default:
            return; // exit this handler for other keys
    }
    $('body').animate({
        scrollTop: currentContainer.getPosition().top + 'px'
    });

});

http://jsfiddle.net/9qhgsysg/1/

答案 1 :(得分:0)

添加此插件https://github.com/flesler/jquery.scrollTo

然后是以下脚本

$(function() {

    function scroll(direction) {

        var scroll, i,
            positions = [],
            here = $(window).scrollTop(),
            collection = $('.container');

        collection.each(function() {
            positions.push(parseInt($(this).offset()['top'], 10));
        });

        for (i = 0; i < positions.length; i++) {
            if (direction == 'next' && positions[i] > here) {
                scroll = collection.get(i);
                break;
            }
            if (direction == 'prev' && i > 0 && positions[i] >= here) {
                scroll = collection.get(i - 1);
                break;
            }
        }

        if (scroll) {
            $.scrollTo(scroll, {
                duration: 600
            });
        }

        return false;
    }

    $("#next,#prev").click(function() {
        return scroll($(this).attr('id'));
    });

    $(".scrollto").click(function() {
        $.scrollTo($($(this).attr("href")), {
            duration: 600
        });
        return false;
    });

});

next和prev id都有.scrollto类。

以上js允许您创建一个固定位置next / prev nav,并且允许您向上或向下滚动到最近的容器。

<div class="toolbar">
 <a id="next" class="scrollto">Next</a>
 <a id="prev" class="scrollto">Prev</a>
</div>