Pergunta

Implementei com sucesso o plug -in do ScrollTo JQuery que rola para a próxima div com a classe "Novo" quando um link é clicado. No entanto, eu também gostaria de usar as teclas de seta para rolar para cima e para baixo para as próximas/anteriores divs da mesma classe.

Eu olhei por toda a Internet, mas não consegui descobrir como fazer isso. Eu sou muito novo no JS, então instruções muito simples seriam apreciadas!

Aqui está o código relevante:

<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>

O que preciso adicionar a isso para fazer as teclas de seta funcionarem?

Obrigado, Ted

Foi útil?

Solução

Você pode usar o keydown ouvinte de eventos para ouvir Keypresses. Você pode usar isso em &lt;input&gt; campos e similares. Porque os eventos KeyDown bolha no DOM, você pode usá -lo no document Objeta para pegar qualquer tecla na página:

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

Cada KeyPress possui um código. Se você usar o código acima em sua página da web, verá que o código da chave para a seta para baixo é 40. Você pode solo isso usando um if ou switch declaração no manipulador:

jQuery(function () {

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

});

Agora você precisa vincular o código que realmente salta para o próximo título. Eu recomendo abstrair o código em uma função para que você possa usá -lo para teclas e cliques. Aqui está a função, juntamente com uma variante do seu código original que o usa:

// 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);

});

Por fim, você pode adicionar o código do KeyPress e chamar a função a partir daí:

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
    }
  });

});

Atualizar: Para rolar para cima, faça duas coisas. Mudar o keydown manipulador para:

  $(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();
    }
  }

e escreva a scrollToLast() função baseada em scrollToNew() Isso encontra o último título novo que não está na página:

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);
  }
}

Outras dicas

Apenas para dar mais ideia, trabalhando com matrizes.

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);      
    }

});

Você precisa capturar o evento KeyPress e decidir qual código de chave foi pressionado

$(document).keypress(function(e) {
    switch(e.keyCode) { 
        case 37:
            //left arrow pressed
        break;
        case 39:
            //right arrow pressed
        break;
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top