function Box() { var animationStartTime = 0; var animationDuration = 500; var target = document.querySelector('.box'); this.startAnimation = function () { animationStartTime = Date.now(); requestAnimationFrame(update); }; function update() { var currentTime = Date.now(); var positionInAnimation = (currentTime - animationStartTime) / animationDuration; var xPosition = positionInAnimation * 100; var yPosition = positionInAnimation * 100; target.style.transform = 'translate(' + xPosition + 'px,' + yPosition + 'px)'; if (positionInAnimation <= 1) { requestAnimationFrame(update); } } } var box = new Box(); box.startAnimation(); var b = document.querySelector('.box'); b.addEventListener('click', function () { box.startAnimation(); }, false);
html { background: #f2f2f2; } .box { width: 100px; height: 100px; background: #fff; box-shadow: 0 10xp 20px rgba(0,0,0,0.5); } @keyframes movingBox { 0% { transform: translate(0, 0); opacity: 0.3; } 25% { opacity: 0.9; } 50% { transform: translate(100px, 100px); opacity: 0.2; } 100% { transform: translate(30px, 30px); opacity: 0.8; } }
<p>click to animate</p> <div class="box"></div>