有条件包括CSS [英] Conditional include of CSS

查看:83
本文介绍了有条件包括CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只有当顶部框架URL包含字符串facebook.com时,我才能使用Javascript来包含CSS文件吗?

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

短伪代码:

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


推荐答案

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

A quick document.write-based solution would be:

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

Or with 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>

这篇关于有条件包括CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆