Html 如果默认值不存在,则回退背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37588017/
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
Fallback background-image if default doesn't exist
提问by djsony90
I want to set an image as a background, however the image name might be either bg.png
or bg.jpg
.
我想将图像设置为背景,但是图像名称可能是bg.png
或bg.jpg
。
Is there any non-javascript way to create a fallback to an alternative image if the default background doesn't exist?
如果默认背景不存在,是否有任何非 JavaScript 方法可以创建备用图像的后备?
body{
background: url(bg.png);
background-size: 100% 100%;
width: 100vw;
height: 100vh;
margin: 0;
}
回答by
You can use multiple backgrounds if there is no transparency involved and they occupy all available space or have the same size:
如果不涉及透明度并且它们占据所有可用空间或具有相同大小,则可以使用多个背景:
div{
background-image: url('http://placehold.it/1000x1000'), url('http://placehold.it/500x500');
background-repeat:no-repeat;
background-size: 100%;
height:200px;
width:200px;
}
<div></div>
If the first doesn't exit, the second will be displayed.
如果第一个不退出,将显示第二个。
div{
background-image: url('http://placehol/1000x1000'), url('http://placehold.it/500x500');
background-repeat:no-repeat;
background-size: 100%;
height:200px;
width:200px;
}
<div></div>
回答by Chris
To specify multiple possible backgrounds, you could do:
要指定多个可能的背景,您可以执行以下操作:
background-color: green;
background-image: url('bg.png'), url('bg.jpg');
This will set the background to bg.png
if it exists. If it doesn't exist, it will be set to bg.jpg
. If none of those images exist, the background will be set to the static green
color.
这会将背景设置为bg.png
是否存在。如果它不存在,它将被设置为bg.jpg
。如果这些图像都不存在,背景将设置为静态green
颜色。
Note that it will prioritize whatever image is specified first. So if both images exist, it will choose the bg.png
over the bg.jpg
.
请注意,它将优先考虑首先指定的任何图像。因此,如果存在两个图像,它会选择bg.png
过bg.jpg
。
Check out the demo here. Test it by breaking any of the image urls'.
回答by DanyAlejandro
Although this solution does involve JS, it will download the first image using CSS, and will onlyuse JS to download the fallback image if the main image failed to download.
虽然这个方案确实涉及到JS,但它会使用CSS下载第一张图片,如果主图下载失败,只会使用JS下载后备图片。
First, set the main image with CSS as usual, for example:
首先,像往常一样用CSS设置主图像,例如:
.myImage {
background-image = "main-image.png";
}
And add the following JS that will only act if loading the main image fails (otherwise, fallback image will never be downloaded).
并添加以下 JS,该 JS 仅在加载主图像失败时才起作用(否则,将永远不会下载后备图像)。
var img = document.createElement("img");
img.onerror = function() {
var style = document.createElement('style');
style.innerHTML = '.myImage { background-image = url("http://fallback_image.png"); }';
document.head.appendChild(style);
}
img.src = "main_image.png";
Note that you can add multiple rules to the CSS block added with javascript, for example if you need to do this with multiple elements.
请注意,您可以向使用 javascript 添加的 CSS 块添加多个规则,例如,如果您需要对多个元素执行此操作。
回答by Tuomas Hietanen
I wanted to have a solution that doesn't load the images twice. For example CDN with a fallback is not very good if it always loads the original images also. So I ended up writing a Javascript to manipulate the loaded CSS DOM.
我想要一个不会两次加载图像的解决方案。例如,如果 CDN 也总是加载原始图像,那么带有后备的 CDN 就不是很好。所以我最终编写了一个 Javascript 来操作加载的 CSS DOM。
var cdn = "https://mycdn.net/"; // Original location or thing to find
var localImageToCssPath = "../"; // Replacement, Css are in /css/ folder.
function replaceStyleRule(allRules){
var rulesCount = allRules.length;
for (var i=0; i < rulesCount; i++)
{
if(allRules[i].style !== undefined && allRules[i].style !== null &&
allRules[i].style.backgroundImage !== undefined &&
allRules[i].style.backgroundImage !== null &&
allRules[i].style.backgroundImage !== "" &&
allRules[i].style.backgroundImage !== "none" &&
allRules[i].style.backgroundImage.indexOf(cdn) > -1
)
{
var tmp = allRules[i].style.backgroundImage.replace(cdn, localImageToCssPath);
//console.log(tmp);
allRules[i].style.backgroundImage = tmp;
}
if(allRules[i].cssRules !== undefined && allRules[i].cssRules !== null){
replaceStyleRule(allRules[i].cssRules);
}
}
}
function fixBgImages(){
var allSheets = document.styleSheets;
if(allSheets===undefined || allSheets===null){
return;
}
var sheetsCount = allSheets.length;
for (var j=0; j < sheetsCount; j++)
{
var allRules = null;
try{
allRules = allSheets[j].cssRules;
} catch(e){
// Access can be denied
}
if(allRules!==undefined && allRules!==null){
replaceStyleRule(allRules);
}
}
}
// use fixBgImages() in e.g. onError