我目前正在设计一个移动优先调查网站,但我无法弄清楚如何使用div
滚动下一个和之前的jQuery
。每个div
都应该是调查问题,点击每个button class="next"
内的div
页面应该滚动到下一个div。
到目前为止,您可以在fiddle
出于某种原因,.current
.container
到目前为止,这是我的jQuery:
(function() {
var scrollTo = function(element) {
$('html, body').animate({
scrollTop: element.offset().top
}, 500);
}
$('#next').click(function(event) {
event.preventDefault();
var $current = $('#container > .current');
if ($current.index() != $('#container > div').length - 1) {
$current.removeClass('current').next().addClass('current');
scrollTo($current.next());
}
});
$('#prev').click(function(event) {
event.preventDefault();
var $current = $('#container > .current');
if (!$current.index() == 0) {
$current.removeClass('current').prev().addClass('current');
scrollTo($current.prev());
}
});
})();
关注我的CSS
.back {
position:fixed;
z-index:1000;
}
.question-container {
height:100%;
padding:2em;
background-color:blue;
margin-top:20px;
}
.current {
color:red;
}
和HTML
<div class="back">
<button class="back" id="back">Back</button>
</div>
<div id="container">
<div class="question-container current">
<h2>Question 1</h2>
<button class="next"> Next
</button>
</div>
<div class="question-container">
<h2>Question 2</h2>
<button class="next"> Next
</button>
</div>
<div class="question-container">
<h2>Question 3</h2>
<button class="next"> Next
</button>
</div>
<div class="question-container">
<h2>Question 4</h2>
<button class="next"> Next
</button>
</div>
<div class="question-container">
<h2>Question 5</h2>
<button class="next"> Next
</button>
</div>
</div>
答案 0 :(得分:0)
我在代码中修改了一些东西来修复它。
演示: http://jsfiddle.net/aamir/Da3qp/4/
(function() {
var scrollTo = function(element) {
console.log(element);
$('html, body').animate({
scrollTop: element.offset().top
}, 500);
}
$('.next').click(function(event) {
event.preventDefault();
var $current = $('#container > .question-container.current');
var $next = $current.next().first();
if ($next.length!=0) {
$current.removeClass('current')
$next.addClass('current');
scrollTo($next);
}
});
//don't use $('.back') since there are two and the event will be triggered twice
$('#back').click(function(event) {
event.preventDefault();
var $current = $('#container > .question-container.current');
var $prev = $current.prev().first();
if ($prev.length!=0) {
$current.removeClass('current')
$prev.addClass('current');
scrollTo($prev);
}
});
})();