纯JS等价于jQuery .animate()
Pure JS equivalent of jQuery .animate()
下面的jQuery动画在纯JavaScript中的等效是什么?
function animate(element, position, speed) {
$(element).animate({
"top": position
}, speed);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
您可以使用setTimeout
和setInterval
方法实现纯javascript的复杂动画。
请在这里核对。
下面是移动元素的关键部分:
function move(elem) {
var left = 0
function frame() {
left++ // update parameters
elem.style.left = left + 'px' // show frame
if (left == 100) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 10) // draw every 10ms
}
这个版本使用了javascript .animate()函数,这是更好或更性能
比requestAnimation帧。,它也是jquery .animate()的合适替代品。
你可以使用迭代,定时函数&填充方法以及雏菊链与其他动画
document.getElementById("Elem");
Elem.style.position = "absolute";
Elem.animate({
top: ['8px', '280px']
},{ duration: 1760, // number in ms [this would be equiv of your speed].
easing: 'ease-in-out',
iterations: 1, // infinity or a number.
// fill: ''
});
我相信setTimeout &setInterval函数都在底层使用不安全的eval()函数,但不是100%确定,只要记住阅读有关它的文章…
别引用我的话!研究一下,
但是我写的代码经过测试是有效的。
setInterval()方法对于浏览器来说太重了,所以最好使用requestAnimationFrame()来制作动画。下面的代码是使用此方法的示例:
let _btns = document.querySelectorAll('.btn'),
_start = null;
let _loop = function (timestamp, duration, position, wrap) {
if (!_start) _start = timestamp;
let progress = (timestamp - _start) / duration;
wrap.style.left = progress * position + 'px'
if ( progress < 1 ) {
window.requestAnimationFrame( function (timestamp){
_loop(timestamp,duration,position,wrap);
} );
} else {
_start = null;
}
},
_animation = function () {
const wrap = document.querySelector('.logo-2'),
position = 300, // 300 pixels
duration = 500; // 500 milliseconds
_loop(0,duration,position,wrap);
},
_addEvents = function () {
[].forEach.call(_btns,function(el){
el.addEventListener('click', function (e) {
_animation();
})
});
},
_init = function() {
_addEvents();
};
_init();
Element.animate()函数似乎非常简单和有用。但目前有很多兼容性问题。你可以阅读:
https://developer.mozilla.org/en-US/docs/Web/API/Element/animate我建议习惯requestanimationframe。它兼容所有的浏览器,它是非常强大的:
https://javascript.info/js-animation相关文章:
- 可以'使用jQuery animate时无法看到动画
- 如何使用jquery animate来回移动多个元素
- jQuery animate()函数没有't设置动画
- JQuery.animate();不以固定高度工作
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 有没有一种方法可以用步骤递归调用jQuery animate()
- jquery animate无法正常工作
- JQuery.animate()菜单幻灯片返回
- jQuery animate只在单击时工作一次
- 如何在不使用css转换的情况下将jQuery animate与css3属性相结合
- Implementation of jQuery 'animate' with Meteor
- jQuery:在 animate 属性上使用变量
- jQuery Animate 在创建图库滑块时不起作用
- jQuery的slideUp,slideDown,animate函数的任何替代品
- jQuery animate 会中断空格键滚动
- Jquery Animate on IE makes error
- 使用 jQuery animate 时绘制一个又一个对象的线条
- ToggleClass animate jQuery?
- $.animate() jQuery显示:表不影响未指定的空间尺寸
- 使用animate() JQUERY获取进度