如果未加载背景图像,按钮文本颜色的回退?

fallback for button text color if background-image is not loaded?

我有一个带有深色背景图像 png 文件和透明胶片的按钮。按钮文字为白色。如果背景图像没有显示,我需要一个后备方法来将按钮文本颜色更改为黑色。如何使用 javascript 完成此操作? 我找到了 CSS transparent background fallback when images are disabled 但这似乎在这里不起作用,而且我不确定如何在 html 代码中正确输入 div。

.btn-was {  
  background-size: 100%;
  background-repeat: no-repeat;
  color:#fff;
  margin-bottom:25px;
  padding:10px;
}

.btn-was {
  background-image: url(../img/button.png);
}
<a class="btn-was" href="#" role="button">About</a>

url() css 中的引用不会引发 success/error 事件,因此测试图像是否加载的唯一方法是实际尝试使用 js[=11 加载它=]

$(".btn-was").each(function() {
    //extract css `background-image` value of this anchor's css
    var bgimg = $(this).css("background-image").match(/url\(["']?([^()]*)["']?\)/).pop();  
    var image = new Image();                   // dummy img for testing
    $(image).error(function() {                // if img didn't load
        console.log(bgimg + " didn't load ");
    $(".btn-was").css('color','black');          // so assign fallback style
    });
    $(image).attr("src", bgimg);               // check if img loads        
});