首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >按钮跳转到下一个锚点

按钮跳转到下一个锚点
EN

Stack Overflow用户
提问于 2019-01-15 16:07:56
回答 1查看 612关注 0票数 1

我有一个wordpress-网站的章节滚动启用,并添加了2个按钮,应该跳到上一页或下一页的网站和2个按钮,应该跳到上一章或下一章的网站。

基于这篇文章,我添加了脚本,但是浏览器返回锚的长度=0,document.getElementByTagName()返回一个大的数组,document.getElementByName()也不起作用。

代码语言:javascript
运行
复制
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;
}

单击按钮时,网站应滚动到网站的下一部分。

编辑: wordpress确实在各自的div:<div ... data-anchor="c_home">中创建了锚点作为数据锚点。以下是仍然不起作用的部分。点击按钮后,网站不会跳转到新的锚点,并且在浏览器的地址行中手动输入锚点也不起作用。JS-Code已经过测试,现在可以正常工作了。

也许缺少跳转的问题是所有的都在一页上?

我通过将最后一行代码更改为以下代码来使其正常工作:

代码语言:javascript
运行
复制
location.href ='#' + nextAnchorName;
location.reload();

现在,它每次点击都会重新加载网站,但它是有效的。这不是我想要的。

EN

回答 1

Stack Overflow用户

发布于 2019-01-15 16:31:35

我更改了var anchors = document.body.getElementsByTagName("a");nextAnchorName = anchors[i++ % iLen].name;

代码语言:javascript
运行
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54194843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档