如果使用css加载图像,如何防止显示图像alt文本

时间:2017-09-06 05:40:00

标签: javascript html css

我通过css grep属性加载图片,而不是使用background属性。但在这种情况下,src文本也会出现。如何停止显示alt文字&仅在未加载图像时显示



alt

.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");
}




2 个答案:

答案 0 :(得分: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">
&#13;
&#13;
&#13;

@Ihazkode收到的css(:after部分)的完成情况。

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

&#13;
&#13;
$('[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);
  });
});
&#13;
.test {
  display: block;
  width: 200px;
  height: 82px;
  background-size: 200px 82px;
}
&#13;
<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">
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

首先我需要知道,有没有将背景图片设置为<img>标签的目的? 如果是,则无需在此处使用<img>标记用户<div>或任何其他标记,而不是使用<img>。 根据W3C标准标记应包含alt="some text",如果找不到<img>来源。