使用 Javascript 创建一个 <link> 元素,然后将其添加到 <head> 部分

Using Javascript to create a <link> element and then adding it to <head> section

我想要完成的是使用 javascript 在该部分中编写一个元素。我尝试添加的 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>

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

这是有效的:

    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 末尾尝试此代码即可。