javascript - 在一个数据属性中为背景图像设置动画
问题描述
我尝试在这些背景图像 url 之间创建一个漂亮的动画,它们存在于一个数据属性中(第一张图像立即加载,5 秒后加载下一张图像,下一张等。在最后一张之后,它从头开始)。
<div data-images="/media/jtjglhbb/main-bg-01.jpg,/media/u2bitolk/main-bg-02.jpg,/media/iasbuo5n/main-bg-04.jpg,/media/f00jm2va/main-bg-03.jpg,"></div>
var $dataImages = $('[data-images]');
var imagesList = $dataImages.data('images').split(',');
$.each(imagesList, function (index, value) {
setTimeout(function () {
$dataImages.stop().animate({ opacity: 0 }, 1000, function () {
$(this).css({ 'background-image': 'url(' + imagesList[index] + ')' })
.animate({ opacity: 1 }, { duration: 1000 });
});
}, 5000);
});
但它没有设置第一个图像,它只在 5 秒后开始,并且它完全不是一个一个地运行,有 5 秒的延迟。
显然逻辑是错误的,一些帮助会很棒。
解决方案
尝试如下。它应该工作。
- 需要图像计数才能使模式值重新开始。
index
将保存图像的索引以在背景中显示changeImage
函数将从内部递归调用,因此它将不断更新背景。- 使用
index = (index + 1) % imageCount;
所以索引将从最后一个索引再次从 0 开始。
var $dataImages = $('[data-images]');
var imagesList = $dataImages.data('images').split(',');
// image count will required to get mode value to start from beginning again.
var imageCount = imagesList.length - 1;
// index of image to show in background
var index = 0;
// function will be called recursively from inside so it will continuously update background.
function changeImage() {
$dataImages.stop().animate({
opacity: 0
}, 1000, function() {
$(this).css({
'background-image': 'url(' + imagesList[index] + ')'
})
.animate({
opacity: 1
}, {
duration: 1000
});
});
// update index to next image url
index = (index + 1) % imageCount;
// declare timeout to call function after required time
setTimeout(changeImage, 5000);
}
changeImage();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div style="height: 150px;" data-images="https://www.w3schools.com/howto/img_nature_wide.jpg,https://www.w3schools.com/howto/img_snow_wide.jpg,https://www.w3schools.com/howto/img_lights_wide.jpg,https://www.w3schools.com/howto/img_mountains_wide.jpg"></div>
推荐阅读
- ios - back4app 数据模型关系过滤
- telegram - 是否可以通过 Telegram Bot 将消息发送到特定的电话号码(不是 chat_id/用户名)?
- react-native - fetch 和 axios 在 PlaidLink 组件中不起作用,我该如何解决?
- swift - 从 Int 变量设置 SwiftUI 键盘快捷键
- reactjs - 如何将具有键和值对的新对象添加到基于类的组件中的现有状态?
- python - 在某个单词之后查找两个字符串之间的字符串
- python - Tornado 测试 - 通过替代 IP 访问 localhost
- plugins - 为什么我收到错误消息,说 Plugins.yml 文件不存在?
- asp.net - MembershipCreateStatus.Success 的奇怪行为
- forms - 制作自定义 Yesod 表单:无法推断(Monad (FormInput m))