我正在尝试实现一个位置:固定滚动到顶部按钮和另一个按部分向下滚动页面的按钮。我已经看到了一个使用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);
}) ;
});
答案 0 :(得分:1)
我使用了与您使用的方法不同的方法,但它似乎完成了工作。
$(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
});
});
});