【问题标题】:Missing background image placeholder缺少背景图片占位符
【发布时间】:2016-12-02 04:40:16
【问题描述】:

虽然似乎有很多关于在无法加载原始图像时处理损坏的<img> 以显示替换图像的答案,但我似乎找不到关于丢失背景图像的解决方案。

问题:如果未加载原始背景图像,如何显示另一个背景图像?

我像这样应用背景图像:

<div style="background-image: url('img/test.jpg');"></div>

【问题讨论】:

  • 我得到的唯一解决方案是使用 JS 检查资源是否可用(使用类似这样的东西:stackoverflow.com/questions/18837735/…),如果不存在则更改 div 属性(或者可能在之前检查设置网址)。
  • 或另一种解决方案,将使用作为 url 的脚本将请求重定向到您想要的图像。对于 PHP,使用类似这样的东西:&lt;?php header( file_exists("img/test.jpg") ? "Location: img/test.jpg" : "Location: img/image_not_available.jpg" ); ?&gt;(当然,这只是一个草稿。)

标签: html css image


【解决方案1】:

您可以使用 javascript 来检查图像的可用性。

var img = new Image();
img.src = 'img/test.jpg';
img.onload = function() {
    // create a script that will append style using background-image with this source
}

img.onerror = function() {
    // create a script that will append style using background-image with new source
}

【讨论】:

    【解决方案2】:

    ▶ 1st 选项 → JavaScript:

    您可以通过发送 AJAX 请求来检查图像在 JavaScript 中是否可用,如下所示:

    function isAvailable(url) {
        var xhttp = new XMLHttpRequest;
        xhttp.onreadystatechange = function() {
            return xhttp.status != 404;
        };
        xhttp.open('head', url, false);
        xhttp.send();
    };
    

    您现在可以使用上述功能进行检查并设置适当的url:

    var element = document.getElementById("element");
    imgUrl = isAvailable("main-url") ? "main-url" : "backup-url";
    element.style.backgroundImage = imgUrl;
    

    ▶ 2nd 选项 → PHP:

    如果您想在服务器端进行检查,那么您可以使用本机 file_exists() 函数,这会变得容易得多:

    <?php
        $img_url = file_exists("main-url") ? "main-url" : "backup-url";
    ?>
    <div style="background-image: url(<?php echo $img_url; ?>);"></div>
    

    【讨论】:

    • 请注意,SO 文档链接在不久的将来会失效,这就是我进行编辑删除链接的原因。
    • 感谢@JoelGritter 的提示,我没有注意到文档正在被删除。我删除了链接?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2022-01-19
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多