简体   繁体   English

使用JS,如何创建访问键以跳至页面的“下一部分”?

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

I have a page with several sections, and each section begins with a H2 tag. 我有一个包含几个部分的页面,每个部分都以H2标签开头。 Each section has a different length from each other. 每个部分的长度互不相同。 I'd like to have two access keys: P and N, for "previous" and "next". 我想要两个访问键:P和N,分别表示“上一个”和“下一个”。

Let's say a user is viewing this page and scrolls to the middle of the page, and is viewing Section 5. If they hit the P access key to go to the previous section, then the browser should jump them to the H2 heading of Section 4. If they hit N to go to the next section, then they should jump to the H2 heading of Section 6. 假设某个用户正在查看此页面并滚动到页面的中间,并且正在查看第5部分。如果他们按P访问键转到上一部分,则浏览器应将其跳转到第4部分的H2标题。 。如果他们按N转到下一部分,则应跳至第6部分的H2标题。

Is it possible to do this, without needing to create a separate access key for every section? 是否可以这样做,而无需为每个部分创建单独的访问密钥? (Eg "1" for Section 1, "2" for Section 2, etc.) (例如,第1部分为“ 1”,第2部分为“ 2”,依此类推)

No you don't have to make separate keys - you only need a pointer to where the user got to and an array of all your sections... Assuming each section starts with H2 here is the code that will do what you want: 不,您不必分别输入键-您只需要一个指向用户到达的位置的指针和所有部分的数组...假设每个部分都以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>

You'll need to build an array of the offsetTop for each matching h2. 您需要为每个匹配的h2建立一个offsetTop数组。

When the user presses 'P' or 'N' you'll need to check the current scrollTop position in the window, and find where this sits on the sections. 当用户按下“ P”或“ N”时,您需要检查窗口中当前的scrollTop位置,并找到它们在各部分中的位置。

From here grab the prev/next position and change the window's scrollTop via scrollTo()... 从这里获取上一个/下一个位置并通过scrollTo()更改窗口的scrollTop ...

It would honestly take more time to write this out, and if you're using a library (jquery, dojo, etc) would make it easier. 老实说,这将花费更多的时间来编写,如果您使用的是库(jquery,dojo等),它将使其变得更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM