以下是 jQuery animate 在纯 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>
以下是 jQuery animate 在纯 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()函数,比requestAnimationFrame更好或性能更高。它也是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。它兼容所有浏览器,而且非常强大。
element.style.top = position + "px";
- VisioN$(element)
应该被定位为absolute
或者relative
。 - Jai