【问题标题】:Navigate to section of page with 'j' and 'k' keys使用“j”和“k”键导航到页面部分
【发布时间】:2011-11-08 15:46:49
【问题描述】:

我正在尝试找到最简单的代码,无论它是独立的还是使用 jQuery 的,这样做:当我按键盘上的 j 时,我被重定向到下面的下一个 div 并且什么时候我按k,我被送回上面的div。滚动流畅的话加分。

【问题讨论】:

  • 你不能给加分所以不要骗我!!!
  • 我的意思是加分,哈哈。 Artemis,我没有看到这个问题,我在发布之前搜索过,但还是很抱歉。

标签: javascript jquery keyboard navigation


【解决方案1】:

我想你会想要使用以下两个插件的组合:

http://plugins.jquery.com/project/hotkeys

http://plugins.jquery.com/project/ScrollTo

你可以以这种方式使用它:

$(document).bind('keydown', 'j', whenyoupressj);
$(document).bind('keydown', 'j', whenyoupressk);

实际滚动的部分可能是:

$.scrollTo( '#someid', 800, {easing:'elasout'} );

【讨论】:

    【解决方案2】:

    我会以这样的方式使用 jQuery:

    $(document).keydown(function (e) {
    
        // Handle only [J] and [K]...
        if (e.keyCode < 74 || e.keyCode > 75) {
            return false;
        }
    
        // Find the "active" container.
        var active = $('div.active').removeClass('active');
        var newActive;
    
        // Handle [J] event.
        if (e.keyCode == 74) {
            newActive = active.next('div');
    
            //if (newActive.index() == -1) {
            //    newActive = $('div', container).last();
            //}
        }
        // Handle [K] event.
        else if (e.keyCode == 75) {
            newActive = active.prev('div');
    
            //if (newActive.index() == -1) {
            //    newActive = $('div', container).first();
            //}
        }
    
        if (newActive !== undefined) {
            newActive.addClass('active');
            $(document).scrollTop(newActive.position().top);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 2013-11-29
      • 2018-04-15
      • 1970-01-01
      相关资源
      最近更新 更多