将箭头键与 jQuery scrollTo 一起使用

发布于 2024-08-20 05:02:12 字数 814 浏览 5 评论 0原文

我已经成功实现了scrollTo jQuery 插件,当单击链接时,该插件会滚动到带有“new”类的下一个div。但是,我还希望能够使用箭头键上下滚动到同一类的下一个/上一个 div。

我查遍了互联网,但无法找到如何做到这一点。我对 JS 很陌生,所以非常简单的说明将不胜感激!

这是相关代码:

<script type="text/javascript">
jQuery(function($){

 $('<div id="next_arrow"></div>') 
  .prependTo("body") //append the Next arrow div to the bottom of the document
  .click(function(){ 
   scrollTop = $(window).scrollTop();
   $('.new').each(function(i, h2){ // loop through article headings
    h2top = $(h2).offset().top; // get article heading top
    if (scrollTop < h2top) { // compare if document is below heading
     $.scrollTo(h2, 800); // scroll to in .8 of a second
     return false; // exit function
    }
   });
  });

});
</script>

我需要添加什么才能使箭头键起作用?

谢谢, 特德

I have successfully implemented the scrollTo jQuery plugin which scrolls to the next div with the class "new" when a link is clicked. However, I would also like to be able to use the arrow keys to scroll up and down to the next/previous divs of the same class.

I have looked all over the internet but have been unable to find out how to do this. I am very new to JS so very simple instructions would be appreciated!

Here is the relevant code:

<script type="text/javascript">
jQuery(function($){

 $('<div id="next_arrow"></div>') 
  .prependTo("body") //append the Next arrow div to the bottom of the document
  .click(function(){ 
   scrollTop = $(window).scrollTop();
   $('.new').each(function(i, h2){ // loop through article headings
    h2top = $(h2).offset().top; // get article heading top
    if (scrollTop < h2top) { // compare if document is below heading
     $.scrollTo(h2, 800); // scroll to in .8 of a second
     return false; // exit function
    }
   });
  });

});
</script>

What do I need to add to this to make the arrow keys work?

Thanks,
Ted

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甜扑 2024-08-27 05:02:12

您可以使用 keydown 事件侦听器来侦听按键。您可以在 <input> 字段等上使用它。由于 keydown 事件 冒泡 DOM,因此您可以在 document 上使用它对象捕获页面上的任何按键:

$(function () {
  $(document).keydown(function (evt) {
    alert("Key pressed: " + evt.keyCode);
  });
});

每个按键都有一个代码。如果您在网页中使用上面的代码,您会看到向下箭头的关键代码是 40。您可以使用 ifswitch 将其单独显示处理程序中的语句:

jQuery(function () {

  $(document).keydown(function (evt) {
    if (evt.keyCode == 40) { // down arrow
      alert("You pressed down.");
    }
  });

});

现在您需要绑定实际跳转到下一个标题的代码。我建议将代码抽象为一个函数,以便您可以将其用于按键和点击。下面是该函数,以及使用它的原始代码的变体:

// Here is the function:

function scrollToNew () {
  scrollTop = $(window).scrollTop();
  $('.new').each(function(i, h2){ // loop through article headings
    h2top = $(h2).offset().top; // get article heading top
    if (scrollTop < h2top) { // compare if document is below heading
      $.scrollTo(h2, 800); // scroll to in .8 of a second
      return false; // exit function
    }
  });
}

// Here is your original code, modified to use the function:

jQuery(function () {

  $("#next").click(scrollToNew);

});

最后,您可以添加按键代码并从那里调用该函数:

function scrollToNew () {
  scrollTop = $(window).scrollTop();
  $('.new').each(function(i, h2){ // loop through article headings
    h2top = $(h2).offset().top; // get article heading top
    if (scrollTop < h2top) { // compare if document is below heading
      $.scrollTo(h2, 800); // scroll to in .8 of a second
      return false; // exit function
    }
  });
}

jQuery(function () {

  $("#next").click(scrollToNew);

  $(document).keydown(function (evt) {
    if (evt.keyCode == 40) { // down arrow
      evt.preventDefault(); // prevents the usual scrolling behaviour
      scrollToNew(); // scroll to the next new heading instead
    }
  });

});

更新: 要向上滚动,请执行两件事。将 keydown 处理程序更改为:

  $(document).keydown(function (evt) {
    if (evt.keyCode == 40) { // down arrow
      evt.preventDefault(); // prevents the usual scrolling behaviour
      scrollToNew(); // scroll to the next new heading instead
    } else if (evt.keyCode == 38) { // up arrow
      evt.preventDefault();
      scrollToLast();
    }
  }

并根据 scrollToNew() 编写一个 scrollToLast() 函数,该函数查找最后一个不存在的新标题在页面上:

function scrollToLast () {
  scrollTop = $(window).scrollTop();

  var scrollToThis = null;

  // Find the last element with class 'new' that isn't on-screen:
  $('.new').each(function(i, h2) {
    h2top = $(h2).offset().top;
    if (scrollTop > h2top) {
      // This one's not on-screen - make a note and keep going:
      scrollToThis = h2;
    } else {
      // This one's on-screen - the last one is the one we want:
      return false;
    }
  });

  // If we found an element in the loop above, scroll to it:
  if(scrollToThis != null) {
    $.scrollTo(scrollToThis, 800);
  }
}

You can use the keydown event listener to listen for keypresses. You can use this on <input> fields and the like. Because keydown events bubble up the DOM, you can use it on the document object to catch any keypress on the page:

$(function () {
  $(document).keydown(function (evt) {
    alert("Key pressed: " + evt.keyCode);
  });
});

Each keypress has a code. If you use the code above in your web page, you'll see that the key code for the down arrow is 40. You can solo this out using an if or switch statement in the handler:

jQuery(function () {

  $(document).keydown(function (evt) {
    if (evt.keyCode == 40) { // down arrow
      alert("You pressed down.");
    }
  });

});

Now you need to bind in the code that actually jumps to the next heading. I recommend abstracting the code out into a function so you can use it for both keypresses and clicks. Here is the function, together with a variant of your original code that uses it:

// Here is the function:

function scrollToNew () {
  scrollTop = $(window).scrollTop();
  $('.new').each(function(i, h2){ // loop through article headings
    h2top = $(h2).offset().top; // get article heading top
    if (scrollTop < h2top) { // compare if document is below heading
      $.scrollTo(h2, 800); // scroll to in .8 of a second
      return false; // exit function
    }
  });
}

// Here is your original code, modified to use the function:

jQuery(function () {

  $("#next").click(scrollToNew);

});

Finally, you can add in the keypress code and call the function from there:

function scrollToNew () {
  scrollTop = $(window).scrollTop();
  $('.new').each(function(i, h2){ // loop through article headings
    h2top = $(h2).offset().top; // get article heading top
    if (scrollTop < h2top) { // compare if document is below heading
      $.scrollTo(h2, 800); // scroll to in .8 of a second
      return false; // exit function
    }
  });
}

jQuery(function () {

  $("#next").click(scrollToNew);

  $(document).keydown(function (evt) {
    if (evt.keyCode == 40) { // down arrow
      evt.preventDefault(); // prevents the usual scrolling behaviour
      scrollToNew(); // scroll to the next new heading instead
    }
  });

});

Update: To scroll upwards, do two things. Change the keydown handler to:

  $(document).keydown(function (evt) {
    if (evt.keyCode == 40) { // down arrow
      evt.preventDefault(); // prevents the usual scrolling behaviour
      scrollToNew(); // scroll to the next new heading instead
    } else if (evt.keyCode == 38) { // up arrow
      evt.preventDefault();
      scrollToLast();
    }
  }

and write a scrollToLast() function based off of scrollToNew() that finds the last new heading that isn't on the page:

function scrollToLast () {
  scrollTop = $(window).scrollTop();

  var scrollToThis = null;

  // Find the last element with class 'new' that isn't on-screen:
  $('.new').each(function(i, h2) {
    h2top = $(h2).offset().top;
    if (scrollTop > h2top) {
      // This one's not on-screen - make a note and keep going:
      scrollToThis = h2;
    } else {
      // This one's on-screen - the last one is the one we want:
      return false;
    }
  });

  // If we found an element in the loop above, scroll to it:
  if(scrollToThis != null) {
    $.scrollTo(scrollToThis, 800);
  }
}
娇纵 2024-08-27 05:02:12

只是为了提供更多想法,使用数组。

var panel_arr = new Array();
$(document).ready(function(e) {

    $('.parallax-panel-wrapper').each(function(i, element){ 
        panel_arr.push( $(this).attr("id") );
    });

    var current_parallax_panel_no   = 0;
    $(document).keydown(function (evt) {
        if (evt.keyCode == 40) { // down arrow
            evt.preventDefault(); // prevents the usual scrolling behaviour
            if(current_parallax_panel_no < (panel_arr.length-1)) current_parallax_panel_no++;
            scrollByArrowKeys(1);               
        } else if (evt.keyCode == 38) { // up arrow
            evt.preventDefault(); // prevents the usual scrolling behaviour
            if(current_parallax_panel_no >= 1) current_parallax_panel_no--;
            scrollByArrowKeys(0); 
        }
    });

    function scrollByArrowKeys(add_more){
        scrollToThis = (($("#" + panel_arr[current_parallax_panel_no]).offset().top)  + add_more ; // get element top
        $.scrollTo(scrollToThis, 800);      
    }

});

Just for giving more idea, working with arrays.

var panel_arr = new Array();
$(document).ready(function(e) {

    $('.parallax-panel-wrapper').each(function(i, element){ 
        panel_arr.push( $(this).attr("id") );
    });

    var current_parallax_panel_no   = 0;
    $(document).keydown(function (evt) {
        if (evt.keyCode == 40) { // down arrow
            evt.preventDefault(); // prevents the usual scrolling behaviour
            if(current_parallax_panel_no < (panel_arr.length-1)) current_parallax_panel_no++;
            scrollByArrowKeys(1);               
        } else if (evt.keyCode == 38) { // up arrow
            evt.preventDefault(); // prevents the usual scrolling behaviour
            if(current_parallax_panel_no >= 1) current_parallax_panel_no--;
            scrollByArrowKeys(0); 
        }
    });

    function scrollByArrowKeys(add_more){
        scrollToThis = (($("#" + panel_arr[current_parallax_panel_no]).offset().top)  + add_more ; // get element top
        $.scrollTo(scrollToThis, 800);      
    }

});
不必在意 2024-08-27 05:02:12

您需要捕获按键事件并确定按下了哪个键码

$(document).keypress(function(e) {
    switch(e.keyCode) { 
        case 37:
            //left arrow pressed
        break;
        case 39:
            //right arrow pressed
        break;
    }
});

You need to capture the keypress event and decide which keycode was pressed

$(document).keypress(function(e) {
    switch(e.keyCode) { 
        case 37:
            //left arrow pressed
        break;
        case 39:
            //right arrow pressed
        break;
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文