2011-02-04 11 views
6

トップフレームのURLに "facebook.com"という文字列が含まれている場合にのみ、CSSファイルを含めるためにJavascriptを使用する方法はありますか?CSSの条件付きの包含

ショート擬似コード:

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

答えて

21

クイックの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> 

や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> 

または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> 
+1

** ':最初の**本当ですか? – qwertymk

+0

ちょうどの場合( - : – arnaud576875

+1

)奇妙なことですが、facebookアプリ( "apps.facebook.com/myapp")内のようです。window.top.location.hostは未定義を返します:/ – Joel

2
<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>