我有以下html:
<article class="layer" id="one"> </article>
<article class="layer" id="two"> </article>
<article class="layer" id="three"> </article>
<section class="cat" id="something">
<article class="layer" id="four"> </article>
<article class="layer" id="five"> </article>
</section>
<article class="layer" id="six"> </article>
…
我想用键盘浏览所有文章。像这样......
var view,
next,
prev;
$(document).keydown(function(e) {
view = $('.layer:in-viewport');
next = view.next().attr('id');
prev = view.prev().attr('id');
switch (e.keyCode) {
case 38: // Up
if ( prev != undefined )
scroll($("#"+prev), true, 0);
break;
case 40: // Down
if ( next != undefined )
scroll($("#"+next), true, 0);
break;
}
});
如果所有文章都在同一个容器中,这将正常工作。但是,正如您在上面所看到的,我还有一些部分包含这些文章。我只是想让它工作好像没有这样的部分,article#three
直接跳到article#four
知道如何才能做到这一点吗?
编辑
导致Firefox中的错误的事情......
if ( top.location.hash ) {
hash = top.location.hash.substring(3);
catHash = hash.split('/')[1];
if ( catHash !== undefined )
scroll($("#"+catHash), false, 0);
else
scroll($("#"+hash), false, 0);
if ( hash != "index" && !isiPhone() )
$('#top').slideDown();
}
只有那4行导致错误......
if ( catHash !== undefined )
scroll($("#"+catHash), false, 0);
else
scroll($("#"+hash), false, 0);
如果当前top.location中存在哈希,则这几行只检查页面加载。
因此,如果网址看起来像www.something.com/#!/category/idOfElement
,我想跳转到页面上的该位置。
为什么这4行只能在firefox中导致这个bug?
答案 0 :(得分:8)
选择“真正的”下一个<article>
元素的最简单方法是使用.index
和.eq
方法。
var allArticles = $("article.layer");
var index = allArticles.index(view); // Zero-based indexes. Not found = -1
var prev = index <= 0 ? $() : allArticles.eq(index-1);
var next = allArticles.eq(index + 1);
答案 1 :(得分:1)
获取所有文章的集合,然后在按键上找出哪个文章是当前文章,并根据当前文章中的相对位置(索引)计算next / prev。处理第一篇/最后一篇文章时需要小心。
var $articles = $('.article');
$(document).keydown(function(e) {
var view = $('.layer:in-viewport'),
idx = $articles.index(view),
prev = $articles.eq(Math.max(0,idx-1)),
next = $articles.eq(Math.min(idx+1,$articles.length-1));
switch (e.keyCode) {
case 38: // Up
if ( prev != undefined )
scroll($("#"+prev), true, 0);
break;
case 40: // Down
if ( next != undefined )
scroll($("#"+next), true, 0);
break;
}
});
如果需要,您还可以在末尾实现包装。