Javascript - 用文本替换破碎的图像(div; css类)

时间:2017-03-19 17:51:52

标签: javascript html css

我试图用JS替换所有破碎的图像。我使用此代码用notfound.png图像替换所有损坏的图像。

    $(document).ready(function() {
    $('img').attr('onError', 'this.src="notfound.png"');
});

无论如何,我想用文字通知代替图片替换它们。我找不到合适的方法,非常感谢你的帮助。 JS不是我的一杯咖啡:(

我想将其用于文本部分:

要显示的文字......

修改 好的,我发现这个解决方案工作正常,但不接受CSS类

<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>').addClass('error404');
});
});
</script>

无论如何,因为我写的CSS类没有被添加,所以这个解决方案并不完整:(

CSS将是:

.error404 {
   display: block;
   color: #667d99;
   font-weight: bold;
   font-size: 11px;
   border: 1px dotted;
   border-radius: 3px;
   padding: 5px;
   margin: 10px;
   background: #e7edf3;
   text-aling: center;
}

5 个答案:

答案 0 :(得分:1)

您可以创建文本节点并将其附加到img的父级,并根据需要选择删除img。此代码位于error

img处理程序内
$('img').on('error', function(){
    $(this).parent().append($('<div>Broken image</div>'));
    $(this).remove();
})

答案 1 :(得分:0)

如果你真的需要使用javascript试试

$(document).ready(function() {
    $('img').attr('alt', 'Alternative text');
});

但是,通过准系统HTML

可以实现同样的目标
<img src="path/to/image.jpg" alt="Alternative text">

答案 2 :(得分:0)

如果您正在使用该图像抛出错误,则可以更改alt。

function imgMissing(image) {
image.onerror = "";
image.alt = "Image not Found";
return true;
}

HTML:

    <img src="image.jpg" onerror="imgMissing(this);" >

答案 3 :(得分:0)

编辑:好的,我发现这个解决方案运行正常:

<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>');
});
});
</script>

无论如何还有一个想法,我需要为这个“div”添加CSS类“error404”,如何在JS中做到这一点?非常感谢你!

CSS将是:

.error404 {
   display: block;
   color: #667d99;
   font-weight: bold;
   font-size: 11px;
   border: 1px dotted;
   border-radius: 3px;
   padding: 5px;
   margin: 10px;
   background: #e7edf3;
}

答案 4 :(得分:0)

好的,我想我找到了适合你的解决方案。我尝试使用jQuery error函数。这个帮助了我:

  

要用另一个替换所有丢失的图像,可以更新传递给.error()的回调内的src属性。确保存在替换图像;否则错误事件将无限期触发。

在你的例子中,这将是最好的:

$('img').each(function() {
    var img = $(this);

    img.error(function() {
        img.replaceWith('<div class="error404">Image not found (error 404)</div>');
    }).attr('src', img.attr('src'));
});

我也为你做了jsFiddle example,这对我很有帮助。