Javascript jQuery 使用淡入/淡出更改 div 背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8610973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery change div background-image with fadeIn/Out
提问by Lior Iluz
I'm trying to create a fadeIn/Out effect on a site I created (edit: site url deleted)
我正在尝试在我创建的站点上创建淡入/淡出效果(编辑:站点 url 已删除)
Everything works great except when you click on one of the colors in the color palette, it replaces the image with no effect.
一切都很好,除了当您单击调色板中的一种颜色时,它会毫无效果地替换图像。
This is the small script I wrote, which is triggered onclick on one of the colors.
这是我写的小脚本,它是在点击其中一种颜色时触发的。
function changeImage(newColor) {
//var previousImage = $('#image-holder').css("background-image");
$('#image-holder').css("background", "url('images/design-" + newColor + ".jpg')");
};
I tried playing with $('#image-holder').fadeOut(1500)
and then $('#image-holder').fadeIn(1500)
but it acts funny... it double fades the image.
我试着玩$('#image-holder').fadeOut(1500)
然后$('#image-holder').fadeIn(1500)
但它的行为很有趣......它使图像双重淡化。
$('#image-holder').css("background", "url('images/design-" + newColor + ".jpg')").fadeOut(function(){$(this).fadeIn()});
What I would like to achieve is onclick on a color box, the current background image will fadeout while the new background image will fade in.
我想要实现的是点击颜色框,当前背景图像将淡出,而新背景图像将淡入。
I know it's easier to achieve that if I'd used two <img src="" />
and switch their display/visibility but I unfortunately I can't alter the HTML that much so I'm looking for a jQuery based solution.
我知道如果我使用两个<img src="" />
并切换它们的显示/可见性会更容易实现,但不幸的是我无法改变 HTML,所以我正在寻找基于 jQuery 的解决方案。
Appreciate the help!
感谢帮助!
采纳答案by Lior Iluz
The solution that worked for me:
对我有用的解决方案:
var image = $('#image-holder');
image.fadeOut(1000, function () {
image.css("background", "url('images/design-" + newColor + ".jpg')");
image.fadeIn(1000);
});
回答by Thank you
This was the only reasonable thing I found to fade a background image.
这是我发现使背景图像褪色的唯一合理方法。
<div id="foo">
<!-- some content here -->
</div>
Your CSS; now enhanced with CSS3 transition.
你的 CSS;现在增强了CSS3 过渡。
#foo {
background-image: url('a.jpg');
transition: background 1s linear;
}
Now swap out the background
现在换掉背景
$("#foo").css("background-image", "url(b.jpg)");
Or do it with native javascript
或者用原生 javascript 来做
document.querySelector("#foo").style.backgroundImage = "url(b.jpg)";
Voilà, it fades!
瞧,它消失了!
Obvious disclaimer:if your browser doesn't support the CSS3 transition
property, this won't work.
明显的免责声明:如果您的浏览器不支持 CSS3transition
属性,这将不起作用。
回答by nidhin nidhi
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = 'images/BasePic1.jpg';
backgrounds[1] = 'images/BasePic2.jpg';
backgrounds[2] = 'images/BasePic3.jpg';
backgrounds[3] = 'images/BasePic4.jpg';
backgrounds[4] = 'images/BasePic5.jpg';
function changeBackground() {
currentBackground++;
if(currentBackground > 4) currentBackground = 0;
$('#image-holder').fadeOut(1500,function() {
$('#image-holder').css({
'background-image' : "url('" + backgrounds[currentBackground] + "')"
});
$('#image-holder').fadeIn(1500);
});
setTimeout(changeBackground, 5000);
}
$(document).ready(function() {
setTimeout(changeBackground, 5000);
});
回答by Benjo
Most solutions just fade in the element, rather than the background. This means that your information is hidden while the background is loading, which is more than often not what you want.
大多数解决方案只是淡入元素,而不是背景。这意味着在加载背景时您的信息是隐藏的,这通常不是您想要的。
I have written the following solution, which works by taking your background image and adding it as an image to the element. It then fades in when it has loaded while all the time keeping your child elements visible.
我编写了以下解决方案,它的工作原理是获取背景图像并将其作为图像添加到元素中。然后它在加载时淡入,同时始终保持您的子元素可见。
It also adds a preloading gif which disappears when it loads. You may need to test with a larger image to see this in action.
它还添加了一个预加载 gif,它在加载时消失。您可能需要使用更大的图像进行测试才能看到它的实际效果。
Code and fiddle/snippet below.
下面的代码和小提琴/片段。
jQuery(document).ready(function() {
jQuery('.Loader').each(function(index, el) {
var sBG = jQuery(this).css('background-image');
sBG = sBG.replace('url(', '').replace(')', '').replace('"', '').replace('"', '');
jQuery(this).prepend('<img src="' + sBG + '" id="tmp_' + jQuery(this).attr('id') + '" class="BGImage" />');
jQuery(this).css('background-image', 'url("http://www.arabianbusiness.com/skins/ab.main/gfx/loading_spinner.gif")');
jQuery(".BGImage:not(.processed)").each(function() {
this.onload = function() {
var oElement = jQuery('#' + jQuery(this).attr('id').replace('tmp_', ''));
jQuery('#' + jQuery(oElement).attr('id')).css('background-image', 'none');
oElement.removeClass('Loader');
jQuery(this).fadeIn(3000);
}
});
});
});
.Loader {
background-position: center;
background-repeat: no-repeat;
transition: background 0.5s linear;
}
.BGImage {
position: absolute;
z-index: -1;
display: none;
}
#Test {
height: 300px;
background-image: url(https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTMa7lFP0VdTl63KgPAOotSies-YQ3qSslOuXWE6FnFxJ_EfF7tsA);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="Test" class="Loader">Some text</div>
回答by Seth
Why not use jQuery to inject the markup that you need?
为什么不使用 jQuery 来注入您需要的标记?
var $image_holder = $('#imageHolder'),
$carousel_container = $('<div/>').attr('id', 'carousel_container'),
images = ['first.jpg', 'second.jpg', 'third.jpg'];
for ( var i=0; i<images.length; i++ )
{
$('<img/>').attr('src', images[i]).appendTo($carousel_container);
}
$carousel_container.insertAfter($image_holder);
$image_holder.hide();
回答by Jason Gennaro
You might want to try something like this
你可能想尝试这样的事情
Replace
代替
$('#image-holder').css("background", "url('images/design-" + newColor + ".jpg')");
$('#image-holder').css("background", "url('images/design-" + newColor + ".jpg')");
with
和
$('#image-holder').animate({background : url('images/design-' + newColor + '.jpg') }, 3000);
$('#image-holder').animate({background : url('images/design-' + newColor + '.jpg') }, 3000);
Adjust the 3000
as necessary to increase the amount of time in the animation.
3000
根据需要调整以增加动画的时间量。
Totally untested
完全未经测试