我已经在顶部设置了一些锚点和一个小菜单。当我点击一个菜单项时,它将滚动到该锚点。转到下一个锚点按钮
我想要做的是在菜单上有一个下一个箭头,以确定我的页面上的下一个锚点并滚动到onClick。
我的锚的#header,#BOX1 - #了Box5
我想如果可能的话用JavaScript来做到这一点。 这里是我的网页在HTML中使用一个onClick
我已经在顶部设置了一些锚点和一个小菜单。当我点击一个菜单项时,它将滚动到该锚点。转到下一个锚点按钮
我想要做的是在菜单上有一个下一个箭头,以确定我的页面上的下一个锚点并滚动到onClick。
我的锚的#header,#BOX1 - #了Box5
我想如果可能的话用JavaScript来做到这一点。 这里是我的网页在HTML中使用一个onClick
东西:
<a href="#" onclick="goToNext();return false;">===></a>
...然后JavaScript的:
var max = 5;
function goToNext() {
var hash = String(document.location.hash);
if (hash && hash.indexOf(/box/)) {
var newh = Number(hash.replace("#box",""));
(newh > max-1) ? newh = 0 : void(null);
document.location.hash = "#box" + String(newh+1);
} else {
document.location.hash = "box1";
}
}
变化max
你想要的最高数量(box1
,box2
等)。不知道这是否会保持动画,但你可以看看一个例子here。只需看地址栏。
有一个名为document.anchors
的HTML集合。要转到下一个定位点,请从网址中获取当前定位点名称,然后在document.anchors
中查找它。如果你找到它,下一个将成为下一个索引。如果您在最后一个索引处,请将锚点设置为第一个。否则,如果没有匹配,只需将其设置为第一个。
这允许您使用任何方案命名锚点,它们将按照它们在DOM中出现的顺序进行访问。
例如
<head>
<!-- Hide script-dependent content -->
<style type="text/css">
.requiresScript-block, .requiresScript-inLine {
display: none;
}
div.spacer {
height: 500px;
border: 1px solid blue;
}
</style>
<script type="text/javascript">
function goToNextAnchor() {
var anchors = document.anchors;
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;
}
// Display script-dependent content if javascript available
document.write(
'\u003Cstyle type="text/css"\u003e' +
'.requiresScript-block {display: block;}' +
'.requiresScript-inLine {display: inline;}' +
'\u003C/style\u003e'
);
</script>
</head>
<body>
<ol>
<li><a href="#header">Go to header</a>
<li><a href="#box1">Go to box 1</a>
<li><a href="#box2">Go to box 2</a>
<li><a href="#box3">Go to box 3</a>
<li><a href="#box4">Go to box 4</a>
<li><a href="#box5">Go to box 5</a>
</ol>
<!-- Only shown if javascript available -->
<button class="requiresScript-inLine" onclick="goToNextAnchor()">Next</button>
<a name="header"></a><h1>Header</h1>
<div class="spacer">content</div>
<p><a name="box1"></a><p>Box 1</p>
<div class="spacer">content</div>
<p><a name="box2"></a><p>Box 2</p>
<div class="spacer">content</div>
<p><a name="box3"></a><p>Box 3 </p>
<div class="spacer">content</div>
<p><a name="box4"></a><p>Box 4</p>
<div class="spacer">content</div>
<p><a name="box5"></a><p>Box 5</p>
</body>