开发者

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. Each section has a different length from each other. I'd like to have two access keys: P and N, for "previous" and "next".

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.

Is it possible to do this, without needing to create a separate access key for every section? (E.g. "1" for Section 1, "2" for Section 2, etc.)


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:

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

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.

From here grab the prev/next position and change the window's scrollTop via scrollTo()...

It would honestly take more time to write this out, and if you're using a library (jquery, dojo, etc) would make it easier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜