簡體   English   中英

如何使用CSS偽元素修復IE對換行符的支持?

[英]How to fix IE support for line break using CSS pseudo-element?

我正在建立一個關於JavaScript References的網站。 對於每個主題,我在標題前面有一個換行符,下面是這個CSS代碼:

h3:before{
    content: "\a";
    white-space: pre;
}

我在所有現代瀏覽器中測試過它,當然,IE 11沒有按預期工作。 我調試了IE,並注意到它上面的屬性是刪除,我認為被其他東西覆蓋,但是進一步調查,我注意到IE的值設置CSS的content: normal; white-space:normal; 這不是我想要的。

CSS攻擊通過

注意:請在IE 11中測試這個jsfiddle代碼 ,你會注意到,在標題之前沒有換行符。

我使用css-pseudo-elements來獲取內容的值,這是我到目前為止在js中所擁有的:

注意:我覺得我不應該這樣做只是為了在IE 11中使CSS換行工作。有沒有更好的方法來使IE瀏覽器識別偽元素w / content屬性?

<!-- Override Fix IE Bug that sets content:normal; & white-space:normal; -->
<script type="text/javascript">
    "use strict";
    //var contentProperty = window.getComputedStyle(document.querySelector('h3'), ':before').getPropertyValue('content');
    //var whiteSpace = window.getComputedStyle(document.querySelector('h3'), ':before').getPropertyValue('white-space');
    var h3 = document.querySelector('h3'), // returns h3
    contentProp = getComputedStyle(h3, ':before').content.toLowerCase().trim(); // returns "\a " ; IE returns "\"\n\""
    console.log("content : ", contentProp);
    if(contentProp !== "\"\\a \"" || contentProp === "normal" || contentProp === "")
    {
        contentProp = "\"\\a\""; // force IE to put value "\a" instead of "\n"

    }
    console.log("content : ", contentProp); // test value again

    var sheet = (function() {
    // Create the <style> tag
    var style = document.createElement("style");

    // Add a media (and/or media query) here if you'd like!
    // style.setAttribute("media", "screen")
    // style.setAttribute("media", "only screen and (max-width : 1024px)")

    // WebKit hack :(
    style.appendChild(document.createTextNode(""));

    // Add the <style> element to the page
    document.head.appendChild(style);

    return style.sheet;
    })();

    // ERROR: IndexSizeError
    sheet.insertRule("h3:before{content: '\a'; white-space: pre;}", 1);
    sheet.addRule("h3:before", "content: '\a'; white-space: pre;", 1);
</script>

此外,當我從IE中的content檢索getComputedStyle()時,其值為"\\n" ,而不是"\\a" ,不確定是否存在問題。

IE 11識別:before偽元素:before ,但它只是不呈現一個只包含換行符的偽元素。 這是否正確是一個有趣的問題,但為了避免在你的情況下的問題,在換行前放置一個不間斷的空間(U + 00A0)。 也就是說,用content: "\\a"替換content: "\\a" content: "\\a0\\a"

另一方面,在h3元素上設置上邊距而不是使用生成的內容添加空行會更容易也更靈活。

我不知道為什么IE開發工具會顯示設置為突破。 這似乎是這些工具中的一個錯誤/功能,因為即使在如上所述修改代碼時也會出現刪除,在這種情況下CSS具有可見效果。 這同樣適用於使用content: "*"進行測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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