js 向document注入css 的方法

js 向document注入css 的方法
應(yīng)用場(chǎng)景:
向iframe內(nèi)的document注入css,覆蓋原有樣式;

方法一:

// inject css to document
export function injectCssToDocument(document, iframeId) {
  let componyRelIframe = document.getElementById(iframeId);
  let iframeDoc = componyRelIframe.contentWindow.document;
  let iframeHead = iframeDoc.getElementsByTagName('head');
  let linkTag = document.createElement('link');
  linkTag.id = 'commonstyle';
  linkTag.href = `/static/css/commonstyle.css`;
  linkTag.setAttribute('rel', 'stylesheet');
  linkTag.setAttribute('type', 'text/css');
  iframeHead[0].appendChild(linkTag)
}

方法二:

/**
 * 在文檔 iframeDocument 中添加樣式
 * @param {*} iframeDocument
 * @param {*} cssText
 */
const addCSS = (iframeDocument, cssText) => {
    var style = iframeDocument.createElement('style'), //創(chuàng)建一個(gè)style元素
        head = iframeDocument.head || iframeDocument.getElementsByTagName('head')[0]; //獲取head元素
    style.type = 'text/css'; //這里必須顯示設(shè)置style元素的type屬性為text/css,否則在ie中不起作用
    if (style.styleSheet) {
        //IE
        var func = function() {
            try {
                //防止IE中stylesheet數(shù)量超過限制而發(fā)生錯(cuò)誤
                style.styleSheet.cssText = cssText;
            } catch (e) {}
        };
        //如果當(dāng)前styleSheet還不能用,則放到異步中則行
        if (style.styleSheet.disabled) {
            setTimeout(func, 10);
        } else {
            func();
        }
    } else {
        //w3c
        //w3c瀏覽器中只要?jiǎng)?chuàng)建文本節(jié)點(diǎn)插入到style元素中就行了
        var textNode = iframeDocument.createTextNode(cssText);
        style.appendChild(textNode);
    }
    head.appendChild(style); //把創(chuàng)建的style元素插入到head中
};

參考:
向iframe嵌入頁面注入css

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容