javascript CSS 动画:移动 div 相对于前一个的新位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26042314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:24:37  来源:igfitidea点击:

CSS animation : move a div with the new position relative to the previous

javascriptcsscss-transitionscss-animations

提问by Matrix

for better performance, I want replace:

为了获得更好的性能,我想替换:

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

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

通过过渡(或动画)CSS3。但是我们如何才能在 CSS 的 left 属性上实现“+=”呢?

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

如何相对于前一个位置移动具有新左位置的 div?

thx.

谢谢。

回答by Oriol

In vanilla-js you can't use +=, but you can get the old value instead:

在 vanilla-js 中,您不能使用+=,但您可以获得旧值:

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>

回答by hitesh upadhyay

You can use the transition for smooth animation. you just put transition settings in the CSS of an element like this,

您可以使用过渡来实现流畅的动画效果。您只需将过渡设置放在这样的元素的 CSS 中,

#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 incrementation of left with script like this.

然后用这样的脚本做你的左增量。

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

You can refer to this page.

你可以参考这个页面