我正在尝试为横跨屏幕的平面制作动画 - 从左侧出来 - 回到右侧。我怎样才能在连续循环中实现这一点?所以它无限期地飞过屏幕,从左侧离开并从右侧飞回来。
我的代码:
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
#animate {
position: relative;
background-image: url(https://www.turbotobias.dk/wp-content/uploads/2019/03/Fly-med-banner-TurboTobias-Graphics2.svg);
width: 500px;
height: 500px;
}
<div id="animate"></div>
$(document).ready(function(e) {
width = "+=" + $(document).width();
$("#animate").animate({
left: width
}, 5000, function() {
// Animation complete.
});
});
最佳答案
您可以通过递归调用执行动画的方法来创建循环。下面的代码片段首先将平面从屏幕向右移动页面宽度。然后它动画到图像的负宽度。完成后,它会等待 2 秒,然后递归调用相同的方法。
function animatePlane ( $plane, pageWidth ) {
$plane.css('left', pageWidth);
$plane.animate({
left: $plane.width() * -1
}, 5000, function(){
setTimeout(function(){
animatePlane($plane, pageWidth);
}, 2000);
});
}
$(document).ready(function() {
animatePlane($('#animate'), $(document).width());
});
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
#animate {
position: absolute;
top: 0;
left: 0;
background-image: url(https://www.turbotobias.dk/wp-content/uploads/2019/03/Fly-med-banner-TurboTobias-Graphics2.svg);
width: 663px;
height: 168px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="animate"></div>
仅 CSS 解决方案
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
#animate {
position: absolute;
top: 0;
left: 100vw;
background-image: url(https://www.turbotobias.dk/wp-content/uploads/2019/03/Fly-med-banner-TurboTobias-Graphics2.svg);
width: 663px;
height: 168px;
animation: slideLeft 5s 2s infinite;
}
@keyframes slideLeft {
from { left: 100vw; }
to { transform: translateX(-200vw); }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="animate"></div>
css 版本使用关键帧与动画属性配对来建立动画。它在屏幕外启动图像,在动画之间等待 2 秒,持续时间为 5 秒。
关于jquery - 动画飞机穿过屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55228769/