我正在尝试创建包含3个主要部分内容的srollTop效果。我有3个部分,第一个是可见的,第二个和第三个是display:none。我希望在单击第一个按钮以显示第二个部分并使用动画隐藏第一个部分然后单击第二个部分上的第二个按钮以执行相同的动画效果隐藏第二个部分并显示第三个部分时实现效果。这是我的代码的示例,直到这一刻。我无法弄清楚如何用动画正确地做到这一点。
$(".button_1").on("click", function() {
$("html, body").animate({
scrollTop: $(".two").offset().top
}, 1000);
$(".two").css({
"display": "block"
});
$(".one").css({
"display": "none"
});
});

body {
height: 3000px;
}
.container {
width: 960px;
margin: 0 auto;
}
.one {
background: red;
width: 100%;
height: 500px;
}
.two {
background: orange;
width: 100%;
height: 500px;
display: none;
}
.three {
background: purple;
width: 100%;
height: 500px;
display: none;
}
.button_1,
.button_2,
.button_3 {
border: 0;
width: 180px;
height: 40px;
background: green;
color: #fff;
display: block;
margin: 0 auto;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="one">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A assumenda ipsam, rem fugit accusantium fugiat ea labore quam impedit, praesentium quisquam. Quia quam, et accusantium labore eius est accusamus perferendis. Lorem ipsum dolor sit amet, consectetur
adipisicing elit. A assumenda ipsam, rem fugit accusantium fugiat ea labore quam impedit, praesentium quisquam. Quia quam, et accusantium labore eius est accusamus perferendis.</p>
<button class="button_1">Click me 1</button>
</section>
<section class="two">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A assumenda ipsam, rem fugit accusantium fugiat ea labore quam impedit, praesentium quisquam. Quia quam, et accusantium labore eius est accusamus perferendis. Lorem ipsum dolor sit amet, consectetur
adipisicing elit. A assumenda ipsam, rem fugit accusantium fugiat ea labore quam impedit, praesentium quisquam. Quia quam, et accusantium labore eius est accusamus perferendis.</p>
<button class="button_2">Click me 2</button>
</section>
<section class="three">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A assumenda ipsam, rem fugit accusantium fugiat ea labore quam impedit, praesentium quisquam. Quia quam, et accusantium labore eius est accusamus perferendis. Lorem ipsum dolor sit amet, consectetur
adipisicing elit. A assumenda ipsam, rem fugit accusantium fugiat ea labore quam impedit, praesentium quisquam. Quia quam, et accusantium labore eius est accusamus perferendis.</p>
<button class="button_3">Do something else</button>
</section>
&#13;
答案 0 :(得分:0)
只有在显示之后才需要滚动到该部分。
我刚刚优化了您的脚本以使用您想要的所有部分。 将班级btn放在所有按钮上。
$(".btn").on("click", function() {
var section = $(this).closest('section');
var next = section.next('section').show();
$("html, body").animate({
scrollTop: next.offset().top
}, 1000);
});
请查看https://jsfiddle.net/6y4qwLbq/1/
如果要隐藏它们,可以使用以下变体:
$(".btn").on("click", function() {
var section = $(this).closest('section');
var next = section.next('section');
section.slideUp();
next.slideDown();
});
https://jsfiddle.net/vjm95303/
一切顺利。