我正在尝试实现一个位置:固定滚动到顶部按钮和另一个逐节向下滚动页面的按钮。我见过类似的使用 ID 的代码,但我想使用节的类和 .next() .closest() 来完成此操作。这可以用 jQuery 实现吗? 滚动到顶部并滚动到第二部分可以工作,但我无法使用 .next() 和 .closest() 跳过第二部分
这是我的 html:
<body>
<a href="#0" class="cd-top">Top</a>
<a href="#2" class="cd-next">next</a>
<div class="section">
<section class="x_section"> 1</section>
<section class="x_section"> 2</section>
<section class="x_section"> 3</section>
<section class="x_section"> 4</section>
</div>
</body>
这是 JavaScript:
jQuery(document).ready(function($){
$next = $('.cd-next'),
$back_to_top = $('.cd-top');
//smooth scroll to top
$back_to_top.on('click', function(event){
event.preventDefault();
$('html,body').animate({ scrollTop: 0 }, 700 );
});
$next.on('click', function(event){
event.preventDefault();
if (typeof advance == 'undefined') {
var fuller = $('section').closest('.x_section').next(),
section = $('.x_section').closest('.x_section').next(),
top0 = section.scrollTop(),
advance = fuller.offset().top;
}
else { var advance = advance + fuller.offset().top; }
$('html,body').animate({ scrollTop: top0 + 408 }, 700);
}) ;
});
这是我的 fiddle : https://jsfiddle.net/pnemeth/uLrjdm7e/
最佳答案
我使用的方法与您使用的方法不同,但它似乎完成了工作。
$(document).ready(function(){
// declare section count, set to 0
var count = 0,
sections = $(".x_section"),
$next = $(".cd-next"),
$top = $(".cd-top");
$next.on('click', function(event){
event.preventDefault();
// increment section count
count++;
$("html, body").animate({
// scroll to section count
scrollTop: $(sections.get(count)).offset().top
});
});
$top.on('click', function(event) {
event.preventDefault();
// reset section count to 0
count = 0;
$("html, body").animate({
scrollTop: $(sections.get(0)).offset().top
});
});
});
更新:此解决方案在技术上满足您使用 .closest() 和 .next() 的要求,但使用位置标记,该位置标记在每次单击按钮后附加到下一个部分 div。当用户单击按钮返回顶部时,标记将附加到第一个部分 div。
$(document).ready(function(){
var $next = $(".cd-next"),
$top = $(".cd-top");
$next.on('click', function(event){
event.preventDefault();
// get section closest to marker
var section = $('#marker').closest('.x_section'),
// get next section
nextSection = section.next();
// remove marker
section.find($('#marker')).remove();
// append new marker to next section
$(section.next()).append('<div id="marker"></div>');
$("html, body").animate({
scrollTop: $(nextSection).offset().top
});
});
$top.on('click', function(event) {
event.preventDefault();
// append marker to first section
$(document).find($('#marker')).appendTo($('.x_section').get(0));
$("html, body").animate({
// scroll to first section
scrollTop: $($('.x_section').get(0)).offset().top
});
});
});
关于javascript - jQuery 滚动到顶部并滚动到下一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42215478/