我試圖顯示img
標記的(外部)html,但我希望alt
屬性顯示爲紅色。如何樣式化圖像的alt屬性
我得到的字符串的方式:
var img_outerHTML = img[0].outerHTML;
這給了我的字符串:
<img alt="main-logo" src="main-logo.png">
所以我怎麼能有main-logo
是紅色的?
謝謝!
編輯
感謝techfoobar
的解決方案和其他人,幫助!
這裏是jsFiddle Example。
我試圖顯示img
標記的(外部)html,但我希望alt
屬性顯示爲紅色。如何樣式化圖像的alt屬性
我得到的字符串的方式:
var img_outerHTML = img[0].outerHTML;
這給了我的字符串:
<img alt="main-logo" src="main-logo.png">
所以我怎麼能有main-logo
是紅色的?
謝謝!
編輯
感謝techfoobar
的解決方案和其他人,幫助!
這裏是jsFiddle Example。
假設你試圖顯示在另一個元素外部HTML正因爲如此,你可以這樣做:
var s = '<img alt="main-logo" src="main-logo.png">';
// As pointed out by user bfavaretto, we need to html-encode it before
// injecting the <span>
s = $('<div/>').text(s).html();
s = s.replace(/alt=\"([a-zA-Z0-9\s-]*)\"/, 'alt="<span class=\'red\'>$1</span>"');
一旦完成,這將HTML字符串轉換爲(注:一切其他的跨度將HTML編碼信用:https://stackoverflow.com/a/1219983/921204)
<img alt="<span class='red'>main-logo</span>" src="main-logo.png">
事實上,這將是:
<img alt="<span class='red'>main-logo</span>" src="main-logo.png">
而在你的CSS,添加:
span.red {
color: red;
}
I + 1ed this,但是reg exp可能可以使用一些工作,因爲它實際上限於值的內容。 – epascarello
是的,特別是'[a-z0-9 \ s - ] *'位。 – techfoobar
@techfoobar,那是我第一次想到。我試過了,但它實際上顯示爲:'
這也可以只CSS來完成。
只是將您的img標籤包裹到span標籤中並將紅色應用於該範圍。 試試這個
你所需要的是一個插件,該ALT標記是由瀏覽器渲染並不能由HTML/CSS單獨改變。 – Matthew
@Matthew,謝謝。你有什麼想法? –
@ m.spyratos閱讀本文http://stackoverflow.com/questions/4216035/css-background-image-alt-attribute?rq=1 – sylwia