2017-09-06 60 views
1

我通过css background属性加载图像,而不是使用src属性。但在这种情况下,alt文本也显示出来。我怎样才能停止显示alt文本&显示它只有在图像不加载如何防止使用css加载图像时显示图像替代文本

.test { 
 
    display: block; 
 
    width: 200px; 
 
    height: 82px; 
 
    background-size: 200px 82px; 
 
    background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJr81CRJeZGFiBsA9_AOyyxegiIPctdcbNfHThnpnclmFH-mJwoQ"); 
 
}
<img class="test" alt="My background image">

+0

尝试使用除img标签以外的div标签以避免显示替代文字。最好使用img标签incase图像失败... – Nandakumar

+0

检查答案在这里https://stackoverflow.com/questions/4216035/css-background-image-alt-attribute –

+0

@brk你可以标记jquery在你的问题? –

回答

1

你可以做一个小动作和隐藏的“文本”在图像内,如果图像没有src属性(或其空)。

(您可以隐藏在许多方面的文本,我选择一个)

.test { 
 
    display: block; 
 
    width: 200px; 
 
    height: 82px; 
 
    background-size: 200px 82px; 
 
    background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJr81CRJeZGFiBsA9_AOyyxegiIPctdcbNfHThnpnclmFH-mJwoQ"); 
 
} 
 

 
img:not([src]) { 
 
    font-size: 0; 
 
    position: relative; 
 
} 
 

 
img:not([src]):after { 
 
    font-size: 18px; 
 
    border: 1px solid black; 
 
    box-sizing: border-box; 
 
    content: attr(alt); 
 
    z-index: -1; 
 
    height: 100%; 
 
    width: 100%; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0 
 
}
<img class="test" alt="My background image">

完成的CSS(中:after部分)从@Ihazkode接收。

为了在图像加载后显示alt,您可以先载入(使用javascript)图像,然后将其放入图像并显示alt。 (上this答案基于)

$('[data-image]').each(function() { 
 
    var $this = $(this); 
 
    var alt = $this.attr('alt'); 
 
    var src = $(this).attr('data-image'); 
 
    $this.removeAttr('alt'); 
 
    
 
    $('<img/>').attr('src', src).on('load', function() { 
 
    $(this).remove(); 
 
    // simulate the delay for heavy image 
 
    setTimeout(function(){ 
 
     $this.css('background', 'url(' + src + ')').attr('alt', alt); 
 
    }, 1000); 
 
    }).on('error', function() { 
 
    $this.attr('alt', alt); 
 
    }); 
 
});
.test { 
 
    display: block; 
 
    width: 200px; 
 
    height: 82px; 
 
    background-size: 200px 82px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img class="test" alt="My background image" data-image="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJr81CRJeZGFiBsA9_AOyyxegiIPctdcbNfHThnpnclmFH-mJwoQ">

+0

@Mosh Feu在这种情况下,如果图像未加载,alt文本将不会显示。这里是一个https://jsfiddle.net/cg6rh4Lu/1/ – brk

+0

@Ihazkode谢谢,但我想他想显示“物理”加载到页面后的图像'alt'。 –

+0

@brk我更新了我的答案,看看。 –

-1

首先我需要知道的,是有背景图片设置为<img>标签的任何目的是什么? 如果是的话,那么没有必要在这里使用<img>标签,用户<div>或任何其他标签,而不是使用<img>。 根据W3C标准标签应该包含alt="some text",如果<img>源找不到。

+0

我不知道为什么倒投了。我的评论按照W3C标准。如果你不知道如何去阅读如何使用HTML标签,然后做代码。在此之前,使用非标准编码是无用的,并且降低了您的代码标准。 –

+0

我是那个倒票的人。我低估了你的评论,因为这是一个评论,而不是一个答案。无论您评论的内容是否有效,都不是答案。请看[回答] –

+0

这个问题没有必要回答大声笑。我不喜欢鼓励这种不必要的事情。我们不是来回答这个问题的。我的观点是他必须明白,他所做的是错误的,他必须理解,如何使用html标签和属性的目的。 首先你应该明白我在投票前所说的话。 –