如何在每次点击时滑动到下一个元素?
How can I slide to the next element per click?
我正在尝试进行 post 导航。单击 "next post" 按钮,然后将 window 滑动到 #post-n
元素。但是 post 数字是随机的,没有等级。我可以制作第一张幻灯片,但不能制作其他幻灯片。
$('.next-post').click(function(e) {
e.preventDefault();
$([document.documentElement, document.body]).animate({
scrollTop: $("#post-2").offset().top
}, 500);
});
.post {
display: block;
height: 500px;
width: 500px;
background-color: #2196F3;
margin-bottom: 30px;
}
.next-post {
position: fixed;
background-color: #f44336;
color: #fff;
padding: 5px;
text-decoration: none;
border-radius: 5px;
bottom: 15px;
left: 50%;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<article id="post-1" class="post"></article>
<article id="post-2" class="post"></article>
<article id="post-3" class="post"></article>
<article id="post-4" class="post"></article>
<article id="post-5" class="post"></article>
<article id="post-6" class="post"></article>
<a href="#" class="next-post">Next Post</a>
这是 JSFiddle:https://jsfiddle.net/xpvt214o/514002/
我跟踪了当前的 post 索引和所有查询的 post
s 作为变量,然后在单击时增加索引并从全局变量中选择该索引:
var currentPostIndex = 0;
var allPosts = $(".post");
$('.next-post').click(function(e) {
e.preventDefault();
currentPostIndex++;
$([document.documentElement, document.body]).animate({
scrollTop: $(allPosts[currentPostIndex]).offset().top
}, 500);
});
我正在尝试进行 post 导航。单击 "next post" 按钮,然后将 window 滑动到 #post-n
元素。但是 post 数字是随机的,没有等级。我可以制作第一张幻灯片,但不能制作其他幻灯片。
$('.next-post').click(function(e) {
e.preventDefault();
$([document.documentElement, document.body]).animate({
scrollTop: $("#post-2").offset().top
}, 500);
});
.post {
display: block;
height: 500px;
width: 500px;
background-color: #2196F3;
margin-bottom: 30px;
}
.next-post {
position: fixed;
background-color: #f44336;
color: #fff;
padding: 5px;
text-decoration: none;
border-radius: 5px;
bottom: 15px;
left: 50%;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<article id="post-1" class="post"></article>
<article id="post-2" class="post"></article>
<article id="post-3" class="post"></article>
<article id="post-4" class="post"></article>
<article id="post-5" class="post"></article>
<article id="post-6" class="post"></article>
<a href="#" class="next-post">Next Post</a>
这是 JSFiddle:https://jsfiddle.net/xpvt214o/514002/
我跟踪了当前的 post 索引和所有查询的 post
s 作为变量,然后在单击时增加索引并从全局变量中选择该索引:
var currentPostIndex = 0;
var allPosts = $(".post");
$('.next-post').click(function(e) {
e.preventDefault();
currentPostIndex++;
$([document.documentElement, document.body]).animate({
scrollTop: $(allPosts[currentPostIndex]).offset().top
}, 500);
});