使用Javascript创建<link>元素并将其添加到<head>部分

6
我想要实现的是使用JavaScript在页面的head部分写入一个link元素。我要添加的link元素如下所示: <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Oswald&effect=neon"> 根据要求,我已经发布了整个代码。
<!doctype html>
<html>
<head>
    <title>Extra-Life Alerts</title>
    <meta charset="utf-8">
    <link href="singleAlert.css" rel="stylesheet">

    <script>
        var effect = $.url().param('effect');
        var font = $.url().param('font');
        /*
         //document.getElementById("body").innerHTML = document.write('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=' + font + '&effect=' + effect +'">');
         //document.getElementById('head').innerHTML += '<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '"">';
         //var stylesheetAdd = '<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '"">';

         $(function() {
         $('head').append('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '""/>');
         });

         //var headID = document.getElementsByTagName("head")[0];
         //$(headID).append('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '"">');
         //document.getElementById('#posts').className = 'font-effect-' + effect;
         //document.getElementById('#posts').style.fontFamily = font;
         //$("#posts").className("font-effect-" + effect).style.fontFamily(font); //= 'font-effect-' + effect;
         //$("#posts").style.fontFamily(font); //= font;
         //if (font) { $('.wf-active body, .wf-inactive body, #posts, body').css('font-family', font); }
         //else{font="Impact"; $('.wf-active body, .wf-inactive body, #posts, body').css('font-family', font);}
         */
        /*
        //$('head').append('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '""/>');
        var stylesheetAdd = '<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="'+font+'"&effect="'+effect+'"">';
        //$('head').append('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Oswald&effect=neon" />');
        $(stylesheetAdd).appendTo(document.head);
        */

        var headID = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = 'http://fonts.googleapis.com/css?family=Oswald&effect=neon';
        headID.appendChild(link);

        /*
        var link = $('<link />')
            .appendTo(document.getElementsByTagName('head')[0])
            .attr('rel', "stylesheet")
            .attr('type', "text/css")
            .attr('href', "http://fonts.googleapis.com/css?family=Oswald&effect=neon");
        $(function(){
           $(link);
        });
        */
    </script>

    <!--<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Oswald&effect=neon">-->
</head>
<body>
<!--<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js"></script>-->
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script src="./javascript/jQuery-url-parser/2.3.1/purl.js"></script>
<script src="./javascript/dropzone/dropzone.js"></script>

<script>
    var checkPriorDonorName = "prior name";
    var getCurrentDonorName = "current name";
    var checkPriorMessage = "prior message";
    var getCurrentMessage = "current message";

    function init() {

        // Parse setup parameters.
        var id = $.url().param('id');
        var audio = $.url().param('audio');
        var playAudio = document.createElement("AUDIO");

        var xmlhttp = new XMLHttpRequest();
        //var url = "http://2dc8c656ef.test-url.ws/tempDonations.txt";
        var url = "http://www.extra-life.org/index.cfm?fuseaction=donorDrive.participantDonations&participantID=" + id + "&format=json";
        xmlhttp.open("GET", url, true);
        xmlhttp.send();

        xmlhttp.onreadystatechange = function () {
            getCurrentDonorName = xmlhttp.responseText;
            getCurrentMessage = xmlhttp.responseText
        };
        getCurrentDonorName = JSON.parse(getCurrentDonorName);
        getCurrentMessage = JSON.parse(getCurrentMessage);

        xmlhttp.onreadystatechange = function () {
            if ((xmlhttp.readyState == '4' && ( xmlhttp.status == '200' || xmlhttp.status == '204' )) &&
                    ( checkPriorDonorName === "prior name" || getCurrentDonorName[0].donorName != checkPriorDonorName ) &&
                    ( checkPriorMessage === "prior message") || getCurrentMessage[0].message != checkPriorMessage) {
                extraLifeAlert(xmlhttp.responseText);
            }
            else
                return;
        };

        /** Debugging steps
         console.log("TEST BEGINNING NAME:   Current: " + getCurrentDonorName[0].donorName + " | Prior: " + checkPriorDonorName);
         console.log("TEST BEGINNING MESSAGE:   Current: " + getCurrentMessage[0].message + " | Prior: " + checkPriorMessage);
         */

        function extraLifeAlert(response) {
            var donorName = JSON.parse(response);
            var message = JSON.parse(response);
            var donationAmount = JSON.parse(response);

            if (donorName[0].donorName) {
                $('#posts').find('.donorName').text(donorName[0].donorName);
            }
            if (donationAmount[0].donationAmount) {
                $('#posts').find('.donationAmount').text(donationAmount[0].donationAmount);
            }
            if (message[0].message !== null) {
                $('#posts').find('.message').text(message[0].message);
            }
            else {
                $("#posts").find(".message").text("");
            }

            //setTimeout(function(){document.getElementById('#posts').attr('style', 'display: none')}, 0);
            //setTimeout(function(){document.getElementById('#posts').attr('style', 'display: inline')}, 2000);
            setTimeout(function () {
                document.getElementById('#posts').style.display = 'none'
            }, 0);
            setTimeout(function () {
                document.getElementById('#posts').style.display = 'inline'
            }, 2000);
            if (audio) {
                playAudio.setAttribute("src", audio);
                playAudio.load();
                playAudio.play();
            }
            setTimeout(function () {
                $("#posts").fadeIn(1000);
            }, 1000);
            setTimeout(function () {
                $("#posts").fadeOut(1000);
            }, 10000);

            checkPriorDonorName = donorName[0].donorName;
            checkPriorMessage = message[0].message;
        }
    }
    /** Debugging steps
     console.log("TEST END NAME:   Current: " + getCurrentDonorName[0].donorName + " | Prior: " + checkPriorDonorName);
     console.log("TEST END MESSAGE:   Current: " + getCurrentMessage[0].message + " | Prior: " + checkPriorMessage);
     */
    setInterval(init, 5000);
</script>

<div id="posts" style="display:none;font-family: Oswald;" class="font-effect-neon">
    <div id="donationMessage"><span class="donorName"></span>&nbsp;Just donated&nbsp;$<span class="donationAmount"></span>.00&nbsp;-&nbsp;<span class="message"></span></div>
</div>
<!--
<script>
    $("#posts").addClass = ( "font-effect-" + effect );
      /*.style.fontFamily(font);/*
     .style.fontFamily(font); //= 'font-effect-' + effect;
     $("#posts").find(".messages").append( $("#posts").hasClass("font-effect-neon").toString() );
     */
</script>
<!--
<script>
    //var font = $.url().param('font');
    //var reload = $.url().param('reload', false);
    //var reloadTime = $.url().param('reloadTime');

    /* Load Googles Webfont API*/

    WebFont.load({
        google: {
            families: [font]
        }
    });

    if (font) {
        $(".wf-active body, .wf-inactive body, #posts").css("font-family", font);
    }
    else {
        font = "Impact";
        $(".wf-active body, .wf-inactive body, #posts").css("font-family", font);
    }

    //if(reload){setInterval(function(){location.reload(true);}, reloadTime);}
</script>-->
</body>
</html>

哎呀,我想我剪切并粘贴了一些东西。所以要让这个谷歌字体和效果起作用,唯一重要的是1)在中添加标签,2)在文本所在的部分添加字体和效果类。现在为了测试目的,我手动输入它。我计划通过脚本控制所有这些,以便用户可以将选项放入url中并使其工作。


这个其他的代码是什么样子?看一下那个也会很有帮助。 - BurningLights
1
为什么要使用过于复杂的 headID?直接使用 document.head 就可以了。 - Sebastian Simon
@Xufox 因为 document.head 只在 IE 9 及以上版本中得到支持。 - Anonymous0day
你为什么要试图使用JS从头部区域添加链接到头部区域??为什么不直接使用你的链接标签?? - Anonymous0day
现在只是为了测试目的。我想添加字体和效果作为用户添加的变量。 - EffOfX
显示剩余5条评论
1个回答

19
这是工作的代码:



    var fontLoader = function (param) {
        var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';

        //link.href = 'http://fonts.googleapis.com/css?family=Oswald&effect=neon';
        document.head.appendChild(link);

        link.href = 'http://fonts.googleapis.com/css?family=' + param.family + '&effect=' + param.effect;


    };

    fontLoader({
        family: 'Oswald',
        effect: 'neon'
    });
.normal , .oswald {
   padding : 3px;
   margin  : 3px;
   color : #333;
   border : solid 1px #CCC;
   font-size : 2em;
  
}
.oswald {
 
  font-family:'Oswald';

}
<div class='normal'>Normal Style</div>
<div class='oswald'>Oswald Style</div>

将以下代码放在页面 body 结尾处,即可实现相关功能。


所以我做的就是在我的<body>标签底部添加了自己的代码,猜猜怎么着,它竟然奏效了!!这对我来说有点奇怪,但我会接受它。如果没有你的建议,我就不会想到这个解决方法! - EffOfX
1
很好,很高兴能帮助你。我认为主要问题来自于 var headID = document.getElementsByTagName('head')[0]; 以及我的评论关于 ...在头部区域中添加一个链接到头部区域中... 在代码到达 </head> 之前没有 TagName('head')[0],我不确定这一点,但这是一个理论。 - Anonymous0day
4
为什么在设置链接前添加元素? - RisingSun
https://dev59.com/nnRB5IYBdhLWcg3w1Kr0#46994943 - Smart Manoj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接