簡體   English   中英

使用JS,如何創建訪問鍵以跳至頁面的“下一部分”?

[英]With JS, how to create an access key to jump to the “next section” on a page?

我有一個包含幾個部分的頁面,每個部分都以H2標簽開頭。 每個部分的長度互不相同。 我想要兩個訪問鍵:P和N,分別表示“上一個”和“下一個”。

假設某個用戶正在查看此頁面並滾動到頁面的中間,並且正在查看第5部分。如果他們按P訪問鍵轉到上一部分,則瀏覽器應將其跳轉到第4部分的H2標題。 。如果他們按N轉到下一部分,則應跳至第6部分的H2標題。

是否可以這樣做,而無需為每個部分創建單獨的訪問密鑰? (例如,第1部分為“ 1”,第2部分為“ 2”,依此類推)

不,您不必分別輸入鍵-您只需要一個指向用戶到達的位置的指針和所有部分的數組...假設每個部分都以H2開頭,則此代碼將執行您想要的操作:

 <script>

  var sections = new Array();



  $(document).ready(function(){
  //get an array of all your sections
  sections = $("h2");
  //your pointer to a current section
  index= 0;
 $(document).keydown(function(event) {
 //previous 'p'
  if (event.keyCode == '80') {

  if (index!=0) {
  index--;
  } else {
  //wrap navigation (go tot the last item if on first item)
  index = sections.length-1;
  }

   jump(sections[index]);
     event.preventDefault();

   }
   //next 'n'
     if (event.keyCode == '78') {
if (index<sections.length-1) {
     index++;
     } else {
     //wrap navigation (go the the first item if on last item)
     index = 0;
     }

     jump(sections[index]);
     event.preventDefault();
   }
   })
})

function jump(obj){
   var new_position = $(obj).offset();
    window.scrollTo(new_position.left,new_position.top);

}
</script>

您需要為每個匹配的h2建立一個offsetTop數組。

當用戶按下“ P”或“ N”時,您需要檢查窗口中當前的scrollTop位置,並找到它們在各部分中的位置。

從這里獲取上一個/下一個位置並通過scrollTo()更改窗口的scrollTop ...

老實說,這將花費更多的時間來編寫,如果您使用的是庫(jquery,dojo等),它將使其變得更容易。

暫無
暫無

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

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