javascript - 使用淡入淡出改变背景图像
问题描述
我正在尝试用 JS 更改我的英雄部分的背景图像。循环正在工作,但我不确定如何让一张图像淡入下一张。
当前设置的方式使其在更改之间淡化为白色(背景色),而不是从一个图像淡化到下一个图像。
var images = ["../images/winter.jpeg", "../images/spring.jpeg", "../images/summer.jpeg", "../images/welcome.jpeg"];
var index = 0;
function changeBackground() {
index = (index + 1 < images.length) ? index + 1 : 0;
$('.hero').fadeOut(0, function () {
$(this).css('background-image', 'url(' + images[index] + ')')
$(this).fadeIn(0);
});
};
var timer = null;
function startSetInterval() {
timer = setInterval(changeBackground, 2000);
}
// start function on page load
startSetInterval();
$('.link-block-animation').hover(
function () {
clearInterval(timer);
},
function () {
timer = setInterval(changeBackground, 2000);
});
解决方案
您可以做的一件事是在.hero
元素上使用绝对定位。每次你想改变背景时,你可以在旧.hero
的. 要使用绝对定位,您可以添加一个带有. 这样,您可以确保所有元素都位于完全相同的位置。所以你的 html 和 css 可能看起来像这样:display:none
.hero
position:relative
.hero
<style>
.container{
position:relative;
height:100px;
width:100px;
}
.hero{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
}
</style>
<div class="container">
<div class="hero"></div>
</div>
现在,使用 javascript,您可以将 a 添加.hero
到容器中,该容器将显示在顶部。由于我们想让它淡出,我们首先设置display
为 none,然后淡入。淡入后我们可以删除旧的.hero
. 像这样的东西:
var index = 0;
$('.hero').css('background-image', 'url(' + images[index] + ')');
function changeBackground() {
var oldHero = $('.hero');
var newHero = $('<div class="hero"></div>');
index = (index + 1 < images.length) ? index + 1 : 0;
newHero.css('display','none');
newHero.css('background-image', 'url(' + images[index] + ')');
$('.container').append(newHero);
newHero.fadeIn(1000,function(){
oldHero.remove();
});
};
这是否接近您的需要?
推荐阅读
- r - R glm.nb 预测三个变量返回错误
- radio-button - TailwindCSS - 选中单选按钮时更改标签
- c - 无缘无故出现hackerrank问题的运行时错误?
- javascript - 测试特定的数字序列是否在整数javascript中
- python - 如何在另一个矩阵中间插入一个矩阵
- r - R中是否有一个函数可以在时间记录中断之前读取最后30秒的时间?
- drools - 用于drools业务中心工作台的Nginx反向代理
- firebase - 如何从 Firebase 实时数据库中获取数据并使用 Flutter 将其放入列表中?
- webpack - 我在 Webpack 中收到 .css 模块解析失败错误,即使我已经在 module.rules 中有一个 css-loader
- python - Pandas Groupby 除了列并取该列的第一个值