簡體   English   中英

使用箭頭鍵瀏覽頁面

[英]Navigate through Page with Arrow Keys

我想允許用戶使用鍵盤上的箭頭鍵瀏覽我的頁面。 對於每一次印刷,我希望他們能夠轉到索引的下一部分,除非專注於輸入字段。

我的代碼的基本結構是這樣的:

  <body>
      <section id="main">
          <!--CONTENT-->
      </section>
      <section id="creation">
          <!--CONTENT-->
      </section>
      <section id="about">
          <!--CONTENT-->
      </section>
      <section id="contact">
          <!--CONTENT-->
      </section>
  </body>


section {
    height: 100vh;
    width: 100%;
    position: relative;
}

我以自己的願景實現了jsFiddle ,該如何實現。 我假設您可以使用jQuery。 按下向上或向下箭頭會將用戶移至下一部分或上一部分,並用紅色邊框突出顯示該部分。 碼:

$(document).keydown(function (e) {
  var $activeSection = $("section.active"),
    $newActiveSection;
    if (e.which == 38) {
    // Up
        $newActiveSection = $activeSection.prev("section");
    if(!$newActiveSection.length) {
        $newActiveSection = $("section").last();
    }
  } else if (e.which == 40) {
    // Down
    $newActiveSection = $activeSection.next("section");
    if(!$newActiveSection.length) {
        $newActiveSection = $("section").first();
    }
  }
  $activeSection.removeClass("active");
  $newActiveSection.addClass("active");
  scrollToObject($newActiveSection);

  e.preventDefault();
});

function scrollToObject(object) {
    $(window).scrollTop(object.offset().top);
}

您需要為此添加JavaScript代碼。 似乎JQuery可以成為完成這項工作的正確工具。 應該是這樣的:

$(function() {
  var allowKeypressNavigation = true;
  var $body = $('body');
  var $activeSection = $('#main');

  //set active section
  function setPrevSectionActive() {
    if($activeSection.is(':first-child')) {
      $activeSection = $activeSection.siblings().last();
    } else {
      $activeSection = $activeSection.prev();
    }
  }

  function setNextSectionActive() {
    if($activeSection.is(':last-child')) {
      $activeSection = $activeSection.siblings().first();
    } else {
      $activeSection = $activeSection.next();
    }
  }

  //scroll to active section
  function scrollToActiveSection() {
    var location = $activeSection.offset().top;
    $body.scrollTop(location);
  }

  //disable keyboard navigation when input in focus
  $('input').on("focus", function(e){
    allowKeypressNavigation = false;
  }).on("blur", function(e){
    allowKeypressNavigation = true;
  });

  //assing event to document
  $(document).on("keydown", function(e){
    if(allowKeypressNavigation) {
      var keyCode = e.keyCode;
      if(keyCode==38) {
        //UP pressed
        setPrevSectionActive();
        scrollToActiveSection();
      } else if(keyCode==40) {
        //DOWN pressed
        setNextSectionActive();
        scrollToActiveSection();
      }
    }
  });
});

我為此添加了一個關於plunker工作示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM