首頁  >  文章  >  web前端  >  使用js和jquery建立link標籤用法實例詳解

使用js和jquery建立link標籤用法實例詳解

伊谢尔伦
伊谢尔伦原創
2017-07-21 09:27:094672瀏覽

相信有很多做前端的朋友碰到過需要用 JavaScript 動態建立樣式表標籤-link標籤。這裡我們就來談談如何在瀏覽器中動態建立link標籤。

使用jQuery 建立link 標籤

如果你開發中喜歡用jQuery,那麼用jQuery在建立link標籤應該是這樣的:

var cssURL = '/style.css',
    linkTag = $(&#39;<link href="&#39; + cssURL + &#39;" rel="stylesheet" type="text/css" media="&#39; + (media || "all") + &#39;" charset="&#39;+ charset || "utf-8" +&#39;" />&#39;);
// 请看清楚,是动态将link标签添加到head里   
$($(&#39;head&#39;)[0]).append(linkTag);

使用原生JavaScript 建立link 標籤

如果你喜歡純天然的JavaScript,就要需要這麼寫:

var head = document.getElementsByTagName(&#39;head&#39;)[0],
    cssURL = &#39;/style.css&#39;,
    linkTag = document.createElement(&#39;link&#39;);
 
    linkTag.id = &#39;dynamic-style&#39;;
 linkTag.href = cssURL;
 linkTag.setAttribute(&#39;rel&#39;,&#39;stylesheet&#39;);
 linkTag.setAttribute(&#39;media&#39;,&#39;all&#39;);
 linkTag.setAttribute(&#39;type&#39;,&#39;text/css&#39;);
 
head.appendChild(linkTag);

IE 里特有的方法createStyleSheet

IE 里特有的方法createStyleSheet 方法也是很方便。

var head = document.getElementsByTagName(&#39;head&#39;)[0],
    cssURL = &#39;themes/BlueNight/style.css&#39;,
 // document.createStyleSheet 的同时就已经把link标签添加到了head中了,怎么讲呢,倒是挺方便
    linkTag = document.createStyleSheet(cssURL);


createStyleSheet( [sURL] [, iIndex])方法接受兩個參數,sURL就是CSS檔案的URL路徑。 iIndex 為可選參數,指插入的link在頁面中stylesheets collection的索引位置,預設是在最後新增建立的樣式。

基本上都介紹完了,來看看完整的解決方案:

function createLink(cssURL,lnkId,charset,media){ 
var head = $($(&#39;head&#39;)[0]),
    linkTag = null;
 
 if(!cssURL){
     return false;
 }
 
 linkTag = $(&#39;<link href="&#39; + cssURL + &#39;" rel="stylesheet" type="text/css" media="&#39; + (media || "all") + &#39;" charset="&#39;+ charset || "utf-8" +&#39;" />&#39;);
  
 head.append(linkTag);
}
function createLink(cssURL,lnkId,charset,media){ 
    var head = document.getElementsByTagName(&#39;head&#39;)[0],
        linkTag = null;
  
 if(!cssURL){
     return false;
 }
    
 linkTag = document.createElement(&#39;link&#39;);
 linkTag.setAttribute(&#39;id&#39;,(lnkId || &#39;dynamic-style&#39;));
 linkTag.setAttribute(&#39;rel&#39;,&#39;stylesheet&#39;);
 linkTag.setAttribute(&#39;charset&#39;,(charset || &#39;utf-8&#39;));
 linkTag.setAttribute(&#39;media&#39;,(media||&#39;all&#39;));
 linkTag.setAttribute(&#39;type&#39;,&#39;text/css&#39;);
    linkTag.href = cssURL; 
 
    head.appendChild(linkTag); 
}


以上是使用js和jquery建立link標籤用法實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn