簡體   English   中英

如果使用css加載圖像,如何防止顯示圖像alt文本

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM