如果不重新加载整个页面,div数据锚就无法工作



我有一个用wordpress创建的网站,它有不同的章节,一个div代表一个页面。在底部我有一个按钮,你可以用它转到下一个div。脚本基本上可以工作,但网站不会在不重新加载页面的情况下跳转到div。这个问题和这个问题有关:跳到下一个锚点的按钮。

锚点作为数据锚点存储在divs:<div ... data-anchor="c-home">中,我想使用以下脚本从一个div跳到下一个div:

function goToNextSection(){
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;
}
document.location.hash ='#' + nextAnchorName;
document.location.reload();

如果没有reload()-命令,浏览器的地址行将被更新,但实际的向下滚动将不起作用。如果我用鼠标滚动,则地址行中的锚点会正确更新。然而,手动更改地址线中的锚也不会跳转到该段。

有人能帮忙吗?

在更新位置时,不需要使用'#'前缀。hash。

document.location.hash ='#' + nextAnchorName;更改为简单的document.location.hash = nextAnchorName;

看看这个jsfiddle。

最新更新