jQuery .animate 走错了方向,为什么

jQuery .animate goes wrong direction why?

本文关键字:为什么 方向 错了 animate jQuery      更新时间:2023-09-26

这是我的CSS:

.animate-rectangle {
    background-color:#0F0;
    border: 1px solid #FFF;
    float:left;
    position:absolute;
    width:100px;
    height:100px;
}

和jQuery代码:

<!--Jquery Code to Animate Rectangle from Left to Right-->
$(document).ready(function () {
    var windo_width = $(document).width() - 300;
    $("#reset").click(function () {
        $(".animate-rectangle").animate({
            "left": "100px"
        }, "slow");
    });
    $("#MoveRight").click(function () {
        $(".animate-rectangle").animate({
            "left": "+=" + windo_width
        }, "slow");
    });
});

看看jQuery代码,它声明了animate({"left":"100px"},但在行动中,它是正确的为什么会发生这种情况?

在查看css时,您最初没有为元素分配left。因此,默认情况下,它将left视为0。所以现在你试图animate左到100,显然你的元素会向右移动,以便从0 to 100移动。尝试为元素设置初始左位置。

  ***    ------>         ***
  ***                    *** 
  |                      |
  |                      |
  left : 0               left: 100

首先,.animate-rectangleleft位置将是 0 ,或者它最接近的相对父级的left值。动画将其向右移动,因为值 100 大于其原点。如果要将其相对于开始位置向右移动100px,请使用+=100px

$("#reset").click(function () {
    $(".animate-rectangle").animate({
        "left": "+=100px"
    }, "slow");
});