示例:jsfiddle
<style>
#slider-outer {
width: 400px;
overflow: hidden;
}
#slider-inner {
width: 1200px;
overflow: visible;
height: 200px;
position: relative;
}
#slider-inner div {
background: ;
width: 200px;
height: 200px;
float: left;
}
.a{background: red;}
.b{background: green;}
.c{background: blue;}
.d{background: yellow;}
.e{background: grey;}
.f{background: coral;}
.g{background: olive;}
</style>
<div id="slider-outer">
<div id="slider-inner">
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
<div class="e"></div>
<div class="f"></div>
<div class="g"></div>
</div>
</div>
$(document).ready(function(){
$('#slider-inner').click(function(){
var scrollAmount = $(this).width() - $(this).parent().width();
var currentPos = Math.abs(parseInt($(this).css('left')));
var remainingScroll = scrollAmount - currentPos;
var nextScroll = Math.floor($(this).parent().width() / 2);
if (remainingScroll < nextScroll) {
nextScroll = remainingScroll;
}
if (currentPos < scrollAmount) {
$(this).animate({'left':'-=' + nextScroll}, 'slow');
console.log(currentPos)
}
else {
$(this).animate({'left':'0'}, 'fast');
}
});
});
我正在经历学习 jQuery 和一些 javascript 的过程,我遇到了这个简单 slider 的示例,并且正在浏览代码行并理解它是如何工作的。除了 var = currentPos
返回到控制台的值之外,我理解了所有内容。
该值在第一次点击时返回 0,这让我很困惑,因为我认为它应该是 -200px
因为 slider 内部正在将 -200px
向左移动?
有人可以解释一下为什么变量将其值返回到控制台吗?
谢谢
最佳答案
console.log
语句不会等待动画完成,即使等待了,currentPos
也将保持为 0,因为动画不会改变变量的值。
理解差异的更好方法是:
if (currentPos < scrollAmount) {
$(this).animate({'left':'-=' + nextScroll}, 'slow', function(){
console.log("After the animation has completed: " + $(this).css('left'));
});
console.log("Before the animation has completed: " + $(this).css('left'))
}
.animate()
的第三个参数是一个匿名函数,将在动画完成时执行。
这将输出:
Before the animation has completed: 0px
After the animation has completed: -200px
这希望更符合您的期望。
关于javascript - "Math.abs(parseInt($(this).css(' left ')"返回与预期不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27562517/