How can I make a link go to the next anchor on the page without knowing anchor name?

旧城冷巷雨未停 提交于 2019-12-29 09:17:09

问题


I have a button at the top of the page, and I want to code it to proceed to the next anchor regardless of what it is. Actually I will want to do next / previous buttons to go to next and previous anchors. This button is on a static frame so it should scroll the rest of the page ideally.

Any suggestions would be great. Again I won't know what the anchor is, this is more like a chapter navigation using a generic button.

Seems like finding next anchor object in the dom and go there should be a doable thing but I'm not a whiz in jquery or javascript to do that.


回答1:


var index = -1;

$('.next').click(function() {
   index++;
   $(window).scrollTop($('a').eq(index).position().top);

});
$('.previous').click(function() {
   index--;
   if(index < 0) { index = 0;}

   $(window).scrollTop($('a').eq(index).position().top);
});



回答2:


A good solution would be to set the 'current' anchor using a class (maybe hard code the first anchor on the page with class='current'), and then use jquery to go through the dom and choose the next or previous anchor. Assuming you have 'next' and 'previous' buttons, you could do something like:

<script type="text/javascript">

  $('.next').click(function(e){
    e.preventDefault();
    var current_anchor = $('a.current');
    var next_anchor = current.next('a');
    $('body').animate({scrollTop:next_anchor.offset().top});
  })

  $('.previous').click(function(e){
    e.preventDefault();
    var current_anchor = $('a.current');
    var previous_anchor = current.prev('a');
    $('body').animate({scrollTop:previous_anchor.offset().top});
  })

</script>


来源:https://stackoverflow.com/questions/13225621/how-can-i-make-a-link-go-to-the-next-anchor-on-the-page-without-knowing-anchor-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!