你可以做一个小动作和隐藏的“文本”在图像内,如果图像没有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">
尝试使用除img标签以外的div标签以避免显示替代文字。最好使用img标签incase图像失败... – Nandakumar
检查答案在这里https://stackoverflow.com/questions/4216035/css-background-image-alt-attribute –
@brk你可以标记jquery在你的问题? –