[英]With JS, how to create an access key to jump to the “next section” on a page?
我有一个包含几个部分的页面,每个部分都以H2标签开头。 每个部分的长度互不相同。 我想要两个访问键:P和N,分别表示“上一个”和“下一个”。
假设某个用户正在查看此页面并滚动到页面的中间,并且正在查看第5部分。如果他们按P访问键转到上一部分,则浏览器应将其跳转到第4部分的H2标题。 。如果他们按N转到下一部分,则应跳至第6部分的H2标题。
是否可以这样做,而无需为每个部分创建单独的访问密钥? (例如,第1部分为“ 1”,第2部分为“ 2”,依此类推)
不,您不必分别输入键-您只需要一个指向用户到达的位置的指针和所有部分的数组...假设每个部分都以H2开头,则此代码将执行您想要的操作:
<script>
var sections = new Array();
$(document).ready(function(){
//get an array of all your sections
sections = $("h2");
//your pointer to a current section
index= 0;
$(document).keydown(function(event) {
//previous 'p'
if (event.keyCode == '80') {
if (index!=0) {
index--;
} else {
//wrap navigation (go tot the last item if on first item)
index = sections.length-1;
}
jump(sections[index]);
event.preventDefault();
}
//next 'n'
if (event.keyCode == '78') {
if (index<sections.length-1) {
index++;
} else {
//wrap navigation (go the the first item if on last item)
index = 0;
}
jump(sections[index]);
event.preventDefault();
}
})
})
function jump(obj){
var new_position = $(obj).offset();
window.scrollTo(new_position.left,new_position.top);
}
</script>
您需要为每个匹配的h2建立一个offsetTop数组。
当用户按下“ P”或“ N”时,您需要检查窗口中当前的scrollTop位置,并找到它们在各部分中的位置。
从这里获取上一个/下一个位置并通过scrollTo()更改窗口的scrollTop ...
老实说,这将花费更多的时间来编写,如果您使用的是库(jquery,dojo等),它将使其变得更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.