button to jump to next anchor

2019-08-01 03:50发布

I have a wordpress-website with section scrolling enabled and added 2 buttons that should jump to the previous or the next page on the website and 2 buttons that should jump to the previous or next chapter on the website.

based on this post Goto Next Anchor Button I added the script but the browser returns the length = 0 for anchors, document.getElementByTagName() returns an array that is to big and document.getElementByName() didn't work too.

var anchordivs = document.querySelectorAll('[data-anchor][data-id]');
var anchors = anchordivs.length;
var loc = window.location.href.replace(/#.*/,'');
var nextAnchorName = 0;

var anchorName = window.location.hash.replace(/#/,'');


if (anchorName){

    for (var i=0, iLength=anchordivs.length; i<iLength; i++) {
        if (anchordivs[i].dataset.anchor == anchorName) {

            nextAnchorName = anchordivs[i+1 % iLength].dataset.anchor;
        break;
        }
}
}
if (!nextAnchorName){
   nextAnchorName=anchordivs[0].dataset.anchor;
}

window.location.href = loc + '#' + nextAnchorName;
}

On button click the site should scroll to the next section of the website.

EDIT: wordpress did create the anchors as data-anchors in the respective divs: <div ... data-anchor="c_home">. Here is what still does not work. On clicking the button the site does not jump to the new anchor and manually entering a anchor in the adressline of the browser does not work either. The JS-Code is tested and works now.

Maybe the problem for the missing jump is that it is all on one page?

I got it working by changing the last codeline to the following:

location.href ='#' + nextAnchorName;
location.reload();

Now its reloading the site with each click, but it works. That is not what i want.

1条回答
做自己的国王
2楼-- · 2019-08-01 04:18

I changed var anchors = document.body.getElementsByTagName("a"); and nextAnchorName = anchors[i++ % iLen].name;

function goToNextAnchor() {
  var anchors = document.body.getElementsByTagName("a");
  var loc = window.location.href.replace(/#.*/,'');
  var nextAnchorName;

  // Get name of the current anchor from the hash
  // if there is one
  var anchorName = window.location.hash.replace(/#/,'');

  // If there is an anchor name...
  if (anchorName) {

    // Find current element in anchor list, then
    // get next anchor name, or if at last anchor, set to first
    for (var i=0, iLen=anchors.length; i<iLen; i++) {
      if (anchors[i].name == anchorName) {
        nextAnchorName = anchors[i++ % iLen].name;
        break;
      }
    }
  }

  // If there was no anchorName or no match,
  // set nextAnchorName to first anchor name
  if (!nextAnchorName) {
    nextAnchorName = anchors[0].name;
  }

  // Go to new URL
  window.location.href = loc + '#' + nextAnchorName;
}

查看更多
登录 后发表回答