我有一个左滚动画,在首次运行时效果很好。 如果单击该按钮,则滚动将动画到最右边的区域,然后返回到原始位置。 但是,当再次单击该按钮时,内容滚动捕捉到最右侧,滚动回原始位置。 我无法解决问题所在。请帮忙。提前谢谢。
小提琴:http://jsfiddle.net/tXt3T/
HTML:
<div class="main">
<div class="content">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
</div>
<button id="button">Scroll</button>
CSS:
* { margin: 0 auto; padding: 0;} .clearfix {clear:both;}
.wrapper { width: 100%;}
.main { width: 100%; height: 300px; position: relative; overflow: scroll;}
.content { width: 200%; position: absolute; left: -500;}
JS:
var scrollLeftInt, scrollRightInt, scrollTarget,
scrollToLeft = function(t) {
if($(".main").scrollLeft() < scrollTarget) {
$(".main").scrollLeft($(".main").scrollLeft() + (scrollTarget*0.01));
}
else {
clearInterval(scrollLeftInt);
$(".main").scrollLeft(scrollTarget);
scrollRightInt = setInterval(function() {scrollToRight(t);}, t);
}
},
scrollToRight = function() {
if ($(".main").scrollLeft() > 0) {
$(".main").scrollLeft($(".main").scrollLeft() - (scrollTarget*0.01));
}
else {
clearInterval(scrollRightInt);
$("#button").removeAttr('disabled');
$(".main").scrollLeft(0);
scrollLeftInt = ""; scrollRightInt ="";
console.log(scrollRightInt);
}
};
$(function() {
console.log("Script File is working");
$("#button").click(function() {
var t = 10;
$(this).attr('disabled', true);
$(".main").scrollLeft(scrollTarget);
scrollTarget = $(".content").width() - $(".content").parent().width() ;
scrollLeftInt = setInterval(function() {scrollToLeft(t);}, t);
});
});
答案 0 :(得分:1)
删除此行,一旦您不初始化它及其undefined
:
$("#button").click(function() {
var t = 10;
$(this).attr('disabled', true);
// $(".main").scrollLeft(scrollTarget);
scrollTarget = $(".content").width() - $(".content").parent().width() ;
scrollLeftInt = setInterval(function() {scrollToLeft(t);}, t);
});