CSS animation: move div with new position relative to previous

for better performance, I want to replace:

$('#foo').animate({ left: '+=42px' }, 500);


using a CSS3 transition (or animation). But how can we do to implement the "+ =" left property in CSS?

How to move the div with the new left position relative to the previous one?



source to share

2 answers

In vanilla-js, you cannot use +=

, but you can get the old value instead:

document.getElementById('foo').onclick = function() {
  this.style.left = parseFloat(getComputedStyle(this).left) + 42 + 'px';

#foo {
  position: relative;
  left: 0;
  transition: 2s left;

<div id="foo">Click me multiple times</div>

Run codeHide result



You can use a transition for smooth animation. you just set the transition parameters in the CSS of an element like this,

#foo {
    -webkit-transition: all 0.5s ease-out;
    -o-transition: all 0.5s ease-out;
    -moz-transition: all 0.5s ease-out;
    transition: all 0.5s ease-out


Then do your zoom to the left of the script as follows.

$('#foo').css('left', '+=42px');


You can refer to this page .



All Articles