我有一个wordpress-网站的章节滚动启用,并添加了2个按钮,应该跳到上一页或下一页的网站和2个按钮,应该跳到上一章或下一章的网站。
基于这篇文章,我添加了脚本,但是浏览器返回锚的长度=0,document.getElementByTagName()返回一个大的数组,document.getElementByName()也不起作用。
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已经过测试,现在可以正常工作了。
也许缺少跳转的问题是所有的都在一页上?
我通过将最后一行代码更改为以下代码来使其正常工作:
location.href ='#' + nextAnchorName;
location.reload();
现在,它每次点击都会重新加载网站,但它是有效的。这不是我想要的。
发布于 2019-01-15 16:31:35
我更改了var anchors = document.body.getElementsByTagName("a");
和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;
}
https://stackoverflow.com/questions/54194843
复制相似问题