如何删除jQuery无限后台循环中的小故障



我有一个背景图像设置为在10秒的CSS动画上无限循环。我使用jQuery根据用户的屏幕大小来查找图像的高度。然后我使用background-position-y,从0精确到图像的高度。这为任何桌面屏幕大小创建了一个平滑的循环(移动设备将使用单独的bg图像(。

问题:在页面加载时,动画在循环的第一次迭代中似乎无法正常工作。图像缓慢平移10秒;跳跃";返回到原始位置,然后为循环的所有未来迭代正确工作。

寻求关于如何制作第一个动画循环的帮助,前10个循环应该/像其他循环一样工作,路径看起来是无限的。

JS Fiddle:https://jsfiddle.net/bennimbl/7xkyhgz2/3/

查看小提琴,注意它的速度慢了10秒,然后注意它在那之后工作正常。

问题是背景图像的启动设置。

这个代码中有一点混合。似乎有人试图在动画中使用CSS关键帧,但后来放弃了,而是在超时时使用JS/jquery。

这个片段通过去掉JS/jquery动画并返回关键帧来简化事情(这在任何情况下都可以帮助CPU使用(。

该代码已经将CSS变量--height设置为当前视口的高度,因此在关键帧中使用该变量将背景图像从顶部位置0移动到顶部位置--this height。

有一个虚假的:在CSS设置动画后,该设置已被删除。

所做的唯一其他更改是从视口开始将背景图像设置为顶部0,而不是在视口底部。

var fullhdWidth = 1920;
var fullhdHeight = 2685;
var fullhdRatio = fullhdWidth / fullhdHeight;
$('#s1Bg').ready(function() {
var containerWidth = $(this).width();
var containerHeight = $(this).height();
var containerRatio = containerWidth / containerHeight;
var realWidth = null;
var realHeight = null;
if (containerRatio > fullhdRatio) {
realWidth = containerWidth;
realHeight = containerWidth / fullhdRatio;
//alert(realWidth + ' ' + realHeight);
} else {
realWidth = containerHeight * fullhdRatio;
realHeight = containerHeight;
//alert(realWidth + ' ' + realHeight);
}
$('<style>').text(`:root{--height: ${realHeight};}`).appendTo(document.head);

$("#s1Bg").css({
'width': '100vw',
'height': '100vh',
'margin': '0',
'background': '#000000 url("https://iili.io/sVrZXe.jpg") 0% 0%/cover repeat-y',
'animation': 'rideup 10s linear infinite'
});
});
body {
margin: 0;
}
@keyframes rideup {
from {
background-position-y: 0;
}
to {
background-position-y: calc(-1px * var(--height));
}
}
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
</head>
<div id="s1Bg" class="s1-bg"></div>

我对css和gotime函数做了一些更改,从realHeight开始,然后设置为background-position-y: 0的动画。我把一些css移到了css文件中,因为它不属于js文件。虽然我真的不明白为什么它在前一把小提琴中没有成功,但在这一把中却成功了

JS:

$("#s1Bg").css({
'background-position-y': realHeight,
'animation:' : 'rideup 10s linear infinite'
});
var gotime = function() {
$('#s1Bg').animate({
'background-position-y': 0,
}, 10000, 'linear', function() {
$(this).css('background-position-y', realHeight);
gotime();
});
}

CSS:

#s1Bg {
height: 100vh;
width: 100vw;
margin: 0;
background-image: url('https://iili.io/sVrZXe.jpg');
background-size: cover;
}

最新更新