简体   繁体   中英

How to save original div position() for later usage?

I'm currently running an animation sequence with the GSAP JS library.

After running the first instance of the animation, I run an onComplete function saving the current position() for #myDiv

I then try to use the coordX value in the last instance of my animation, however it just turns up as: invalid left tween value: undefined

Any ideas?

var coordX;

function regPosition() {
    coordX = $("#mydiv").position().left;
}

function animationStart() {
    //Initiate animation with onComplete
    tl.to("#mydiv", 0.5, {borderRadius:"50%", width: "35%", onComplete: regPosition})

    //Move #myDiv to another position than registered    
    .to("#mydiv", 0.5, {left: 1000})

    //try to use the original position stored in "coordX"
    .fromTo("#mydiv", 1.5, {left:-800}, {left:coordX});
}
animationStart();

The value of coordX isn't set until onComplete is actually called after the first .to completes. Until then the value is undefined .

So the problem is that at definition time , the value of coordX is undefined , and that is the value you are assigning to left . So when that .to is evaluated, it sees an undefined value.

Perhaps a better way is to initiate the reverse animation within onComplete :

function animationStart() {
    tl.to("#mydiv", 0.5, {
        borderRadius:"50%", 
        width: "35%", 
        onComplete: function() {
            var coordX = regPosition();
            tl.to("#mydiv", 0.5, {left: 1000})
              .fromTo("#mydiv", 1.5, {left:-800}, {left: coordX});
        }
    })
}

Your code has some logical issues regarding timing. it takes some time to do the each step and your onComplete function won't be called until your steps all is done. do not user onComplete callback and just save your coordX before initiating the animation and use it when it's done.

创建一个变量,保存位置介绍并稍后使用..我更喜欢.offset()...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM