"Math.abs(parseInt($(this).css('left')"返回与预期不同的值



示例: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的过程,我遇到了这个简单滑块的例子,并且正在浏览代码行并了解它是如何工作的。我了解了除var = currentPos返回到控制台的值之外的所有内容。

该值在第一次单击时返回 0,这让我感到困惑,因为我认为它应该-200px,因为滑块内部向左移动-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

希望这更符合您的期望。

如果你查看 CSS 规则 #slider-inner ,你会发现它没有明确的left集。

#slider-inner {
width: 1200px;
overflow: visible;
height: 200px;
position: relative;
}

由于没有显式left值,因此默认为 auto 。由于#slider-inner是相对定位的,并且也没有指定right属性,因此它不会收到偏移量。

这意味着left实际上是0px的(这正是您在第一次点击时$(this).css('left')运行时得到的(。 var currentPos = Math.abs(parseInt($(this).css('left')));将该值解析为绝对整数 0 ,并将其存储在变量 currentPos 中。如果您查看之后的所有代码:

    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');
    }
  });
});

其中没有任何东西为currentPos赋值,因此该值保持0。将字符串解析为整数得到的零是文字,而不是对当前值 .left 的引用。即使它是对 DOM 元素的 .left 属性的实时引用,它也不会-200.animate 方法异步运行,console.log紧随其后调用,它可能在调用.animate和控制台输出之间的时间内向左移动了几个像素, 但肯定不是完整的 200 像素。

最新更新