我有一个带有加载更多按钮的博客文章列表。为了可访问性,我想在添加新帖子后更改键盘焦点的位置,以便在加载更多帖子后点击选项卡而不是跳到帖子列表下方的元素,从而将焦点集中在添加的新帖子中的第一个帖子中到列表中。
我的想法是,当按下加载更多按钮时,获取列表中的最后一个
article
,然后在加载其他帖子后将焦点集中在其中的链接。这样,当用户再次单击选项卡时,它将移动到列表中的下一篇文章(我的示例中的第四篇文章)。我假设这是行不通的,因为帖子容器的整个 HTML 都被替换了。考虑到每次按下“加载更多”按钮时所有 HTML 都会动态填充,有没有办法解决这个问题?
let additionalPosts = `
<article>
<a href="#">
<h3>Fourth Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
<article>
<a href="#">
<h3>Fifth Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
<article>
<a href="#">
<h3>Sixth Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
`;
$(function() {
$('.load-more').click(function() {
const $lastPost = $('.post-container article').last();
//console.log($lastPost);
$('.post-container').html($('.post-container').html() + additionalPosts);
$('a', $lastPost).focus();
$(this).hide();
});
});
.post-container {
display:flex;
gap:1.5rem;
flex-wrap:wrap;
margin-bottom:3rem;
}
article {
max-width:33%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<h1>Post List</h1>
<div class="post-container">
<article>
<a href="#">
<h3>First Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
<article>
<a href="#">
<h3>Second Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
<article>
<a href="#">
<h3>Third Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
</div>
<button class="load-more" href="#">Load More</button>
<div>
<h3>Some additional links</h3>
<a href="#">Another Link</a>
<a href="#">Another Link</a>
<a href="#">Another Link</a>
</div>
微小的改变将使这项工作如你所期望的那样工作。
let additionalPosts = `
<article>
<a href="#">
<h3>Fourth Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
<article>
<a href="#">
<h3>Fifth Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
<article>
<a href="#">
<h3>Sixth Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
`;
$(function() {
$('.load-more').click(function() {
const $lastPost = $('.post-container article').last();
$('.post-container').append(additionalPosts);
$(this).hide().blur();
$lastPost.find("a").trigger("focus");
});
$(".post-container").on("focus", "a", function() {
console.log("Focus: " + $(this).closest("article").index());
});
});
.post-container {
display: flex;
gap: 1.5rem;
flex-wrap: wrap;
margin-bottom: 3rem;
}
article {
max-width: 33%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<h1>Post List</h1>
<div class="post-container">
<article>
<a href="#">
<h3>First Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
<article>
<a href="#">
<h3>Second Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
<article>
<a href="#">
<h3>Third Post</h3>
<p>Lorem ipsum dolor sit amet</p>
</a>
</article>
</div>
<button class="load-more" href="#">Load More</button>
<div>
<h3>Some additional links</h3>
<a href="#">Another Link</a>
<a href="#">Another Link</a>
<a href="#">Another Link</a>
</div>