我有一个全宽和高div
的网站(每个div
实际上是一个页面),你可以使用链接和哈希来浏览它们; <a href="#work"></a>
会使用div
的{{1}}将您滚动到页面(全高id
)。
我现在要做的是使用按键进行导航,这样您只需按向上和向下箭头即可浏览每个页面。
我想我可以使用switch语句吗?我遇到的麻烦就是让它充满活力。我想这样做的方法是使用work
并在每次按下一个键时将新哈希添加到末尾,因此转到具有相应window.location
的位置。
使用id
语句我可以做这样的事情......
if
但是我想不出怎么用switch语句来做。我需要一些方法来检查下一个哈希,而不是手动设置它。我做了一些谷歌搜索,发现 var hash = window.location.hash.substring(1), // get hash for current page
url = window.location.pathname; // get url
if (hash == 'home' && e.keyCode == 40) {
window.location = url+'#about' // update location with new hash
}
并认为我可以用它来查找下一个nextAll
的{{1}},就像这样..
attr
这很有效,但很明显它只查找第一个div
并且每次都不会更新,我怎样才能获得下一个var hash = $('.what').nextAll('div:first').attr('id').substring(5);
hash = '#'+hash;
所以我可以使用div
语句像这样?
div
HTML
switch
任何想法?我真的不想使用long if else语句!
答案 0 :(得分:1)
你应该使用jQuery的.next()
代替。
var hash = $('.what').next().attr('id').substring(5)
$('.what').next()
会给你.what
的下一个兄弟。
修改强>
要跟踪哪个div
处于活动状态,您可以像这样添加.active
类:
var hash = $('.active').removeClass('active').next().addClass('active').attr('id').substring(5);
$('.active').next()
将始终在.active
后提供下一个div。
请务必将.active
课程添加到最初在HTML中显示的div
。
编辑2:
根据.active
中的currrent div
,您可以在hash
类向右$(document).ready(function(){})
添加$(document).ready(function(){
var hash = window.location.hash.substring(1)
$('#' + hash).addClass('active');
})
类,从而在任何页面上启用它。
var hash = $('.active').removeClass('active').next().attr('id').substring(5);
将早期行更改为:
.active
您不必在HTML中的初始div
上设置{{1}}课程。