1. 程式人生 > >IMG標簽與before,after偽類

IMG標簽與before,after偽類

cti future put query fine asc 意義 -s 生效

在CSS中總有一些你不用不知道,用到才知道的“坑”。比如今天要談的,把 before, after 偽類用在 <img> 標簽上。
嗯,實際上你用你會發現,在大多數瀏覽器這是無效的,dom中並不會出現你想要的結果。
為什麽會這樣呢?
讓我們回歸到 W3C 標準中尋覓一下,在標準中,before, after 偽類的定義如:

As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element‘s document tree content.

來自 https://www.w3.org/TR/CSS21/generate.html#before-after-content

我們應該註意到所謂 document tree content,對於 img 這種自閉和標簽,似乎不存在 content (內容或後代元素)在標簽中,所以選擇器沒有生效。但這樣的解釋還不夠清晰,實際上標準中還有一行註釋:

Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.

嗯,這回清楚了,對於可替換元素(如 img、input、select 等),標準並沒有清晰定義,這也導致了瀏覽器實現的差異性。
有解決辦法麽?搜了一下是有的(http://stackoverflow.com/questions/5843035/does-before-not-work-on-img-elements):

  1. 使用jQuery

    使用 jQuery 的 before,after 方法:
    javascript
    $(‘.target‘).after(‘<img src="..." />‘);

    實際上,jQuery 只是在目標元素前後插入 dom 而已。

  2. 偽造 content

給 img 這類標簽添加 content 屬性,輸入一些無意義的文本,讓瀏覽器認為標簽含有 content。
如在 CSS 中添加:
css
img {
/ hide the default image /
height:0;
width:0;
/ hide fake content /
font-size:0;
color:transparent;
/ enable absolute position for pseudo elements /
position:relative;
/ and this is just fake content /
content:"I‘m just fake content";
}

但這種方法存在瀏覽器兼容問題。

所以最後還是建議不要做這種嘗試了,給父標簽添加偽類吧。

轉載:https://www.donyell-wang.com/post/codes/imgbiao-qian-yu-before-afterwei-lei

IMG標簽與before,after偽類