[英]How to prevent showing image alt text if image is loaded using css
我通过css 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"); }
<img class="test" alt="My background image">
如果图像没有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">
从@Ihazkode收到的css(部分:after
)的完成情况 。
要在图像加载后显示alt
,您可以先加载(使用javascript)图像,然后将其放入图像并显示alt
。 (根据这个答案)
$('[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>
标签的目的? 如果是,则无需在此处使用<img>
标记user <div>
或任何其他标记,而不是使用<img>
。 根据W3C标准标签应该包含alt="some text"
,如果找不到<img>
source。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.