如何使用上一个和下一个按钮循环浏览锚链接?

时间:2018-09-12 10:00:06

标签: javascript jquery css

我有一个移动导航,其主要功能是使用上一个和下一个按钮在页面中的一组锚链接之间循环。

这是到目前为止我能想到的逻辑:

// Anchor links are set, these are the names
const anchors = ['year-1800s', 'year-1850s', 'year-1900s', 'year-1970s'];
const nextBtn = document.querySelector('.sidebar-mobile-btn-next');
const prevBtn = document.querySelector('.sidebar-mobile-btn-prev');

function navNext() {
}

function navPrev() {
}

nextBtn.addEventListener('click', navNext());
prevBtn.addEventListener('click', navPrev());

编辑:我使用的是Bootstrap scrollspy,因此,如果某个锚链接部分位于视口上,则将有一个“活动”类。我还如何基于“活动”类来检测要去的锚点?

2 个答案:

答案 0 :(得分:2)

Below is a solution I created for the same page anchors.
Can be modified to work accordingly and is pretty fast.

<script>
function page() {
var Pnum = parseFloat(document.getElementById("MyNumber").value);

window.location.href="#"+Pnum;

}
</script>

Page: <em  style="font-size:150%;background-color:green;border-radius:4px;position:relative;right:6px;">

<b title="Subtract 1 &#10; Here..." onclick="if (MyNumber.value>1){MyNumber.value=(parseInt(MyNumber.value))-1};page()" style="cursor:pointer"><</b>

<input onchange="page();" style="position:relative;top:-2px;right:1px;width:22px;height:20px;" value="1" alt="1" type="text" id="MyNumber" name="MyNumber" maxlength="2" size="2" min="1" max="99" >

<b title="Add 1 &#10; Here..." onclick="if (MyNumber.value<35){MyNumber.value=(parseInt(MyNumber.value))+1};page()" style="position:relative;right:4px;cursor:pointer">></b>

</em>
<b title="Reset to Current MyNumber" style="position:relative;top:-2px;right:14px;cursor:pointer;background-color:red;" onclick="MyNumber.value=MyNumber.alt;MyNumber.focus();page();return false">&times;</b>&nbsp;
&nbsp;



<!--P1 Start --> <a name="1"></a>

More content Here...


<!--P2 Start --> <a name="2"></a>

More content Here...

<!--P3 Start --> <a name="3"></a>

More content Here...

答案 1 :(得分:1)

这可能是您想要的:

const anchors = ['year-1800s', 'year-1850s', 'year-1900s', 'year-1970s'];
const nextBtn = document.querySelector('.sidebar-mobile-btn-next');
const prevBtn = document.querySelector('.sidebar-mobile-btn-prev');

let index = 0;

function navNext(e) {
  index = (index === anchors.length - 1) ? 0 : ++index;
  e.target.href = `#${anchors[index]}`;
  console.log(e.target.href, index);
}

function navPrev(e) {
  index = (index === 0) ? anchors.length-1 : --index;
  e.target.href = `#${anchors[index]}`;
  console.log(e.target.href, index);
}

nextBtn.addEventListener('click', navNext);
prevBtn.addEventListener('click', navPrev);
<a class="sidebar-mobile-btn-prev" href="#">Prev</a>
|
<a class="sidebar-mobile-btn-next" href="#">Next</a>