简体   繁体   中英

reseting y position of an element in javaScript

i have a canvas who is tweening upwards by a button click. I am trying to make it go back down after the tween is over, but it just does'nt work. It starts off fine at the top of the screen. the first time i click the button it does go down to 400, and then slides up to 200. but on the next click - it would just keep flying up, instead of going back to 400 first. Please help! :)

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <script src=
    "http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
</head>

<body>
    <button onclick="func();">click</button> <canvas height="100" id="canvas"
    style="position:absolute; top:50px; border:3px solid #000000;" width=
    "200"></canvas> 
    <script>
           var c = document.getElementById("canvas");
            function func(){             
                c.style.top = 400 + "px";
                TweenMax.to(c,2,{y: "-=200", onComplete:foo});
            }
            function foo(){
              c.style.top = "400px";
            }
    </script>
</body>
</html>

c.style.top have nothing to do with y modifications from TweenMax once the tweening happened. On a first call of TweenMax.to , TweenMax creates a transform matrix (custom style) on the object, and stops paying attention to regular css properties from this point on.

You have to define startAt: {y: '400px'} in your .to call to force TweenMax to reset tweening to a static value.

The problem is that that this tweening plug-in actually changes transform CSS property to make the transition. Thus, make any changes in elements' style.top won't affect its position, as it is overrode by TweenMax's, browser-specific, transform .

You can use their startAt property to always start at the desired position. I don't recommend this plug-in though, I personally prefer jQuery .

Demo: http://jsfiddle.net/TyZhB/2/

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