2016-11-16 46 views
0

我想允許用戶使用鍵盤上的箭頭鍵瀏覽我的頁面。對於每個媒體,我都希望他們能夠傳遞到索引中的下一部分,除非專注於輸入字段。使用箭頭鍵瀏覽頁面

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

<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; 
} 
+2

我知道你可以用'tabindex'做這個,但不能用箭頭鍵。也許是使用''onkeypress'''''' keypressup''事件監聽器? – Crowes

回答

0

我用我的眼光如何可以實現作出了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); 
} 
0

您需要爲此添加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(); 
     } 
    } 
    }); 
}); 

我爲此添加了一個working example on plunker