javascript CSS 的条件包含

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4900426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:16:47  来源:igfitidea点击:

Conditional include of CSS

javascript

提问by Joel

Is there a way I can use Javascript to include a CSS file only if the top frame URL contains the string "facebook.com"?

仅当顶部框架 URL 包含字符串“facebook.com”时,有没有一种方法可以使用 Javascript 来包含 CSS 文件?

Short pseudo code:

短伪代码:

if top.frame.url.contains("facebook.com"):
   include("style-facebook.css");

回答by Arnaud Le Blanc

A quick document.write-based solution would be:

一个快速的基于 document.write 的解决方案是:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        document.write('<link rel="stylesheet" type="text/css" href="stylefacebook.css" />');
    }
</script>

Or using the dom:

或者使用 dom:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        var lnk = document.createElement('link');
        lnk.type='text/css';
        lnk.href='stylefacebook.css';
        lnk.rel='stylesheet';
        document.getElementsByTagName('head')[0].appendChild(lnk);
    }
</script>

Or with jquery:

或者使用 jquery:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        $('head:first').append('<link rel="stylesheet" type="text/css" href="stylefacebook.css" />');
    }
</script>

回答by naveen

<script type="text/javascript">
//<![CDATA[
if ("condition is satisfied") {
    if (document.createStyleSheet) {
        document.createStyleSheet('http://server/style-facebook.css');
    } else {
        var styles = "@import url(' http://server/style-facebook.css ');";
        var newSS = document.createElement('link');
        newSS.rel = 'stylesheet';
        newSS.href = 'data:text/css,' + escape(styles);
        document.getElementsByTagName("head")[0].appendChild(newSS);
    }
}
//]]>
</script>