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

标签 javascript jquery

示例: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/

相关文章:

javascript - 使用 TweenLite/GSAP 选择 DOM 对象的最佳方式?

javascript - Rxjs/reactor limit operator 等效于 ajax 请求

php - jquery post与$.ajax,如何避免多次发布?

javascript - jQuery Datepicker unix 时间戳

jquery - 如何使用 jquery 在另一个选项卡处于事件状态时删除默认的事件选项卡颜色

javascript - DIV 在 html5 视频之上

javascript - 在 Javascript 中解析 Gmail 批处理响应

javascript - 在 Chrome 中输入类型电子邮件值,重音字符错误

javascript - Joyride 基础自定义覆盖

javascript - 下面的 React.js 代码中 "this"中的关键字 "this.state"指的是什么?