亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript動(dòng)態(tài)創(chuàng)建link標(biāo)簽到head里的方法

 更新時(shí)間:2014年12月22日 09:02:46   投稿:shichen2014  
這篇文章主要介紹了JavaScript動(dòng)態(tài)創(chuàng)建link標(biāo)簽到head里的方法,分別介紹了使用jQuery的方法、使用原生javascript方法與IE特有的createStyleSheet方法等,非常具有實(shí)用價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了JavaScript動(dòng)態(tài)創(chuàng)建link標(biāo)簽到head里的方法。分享給大家供大家參考。具體分析如下:

相信有很多做前端的朋友碰到過需要用 JavaScript 動(dòng)態(tài)創(chuàng)建樣式表標(biāo)簽——link標(biāo)簽。這里我們就來說說如何在瀏覽器中動(dòng)態(tài)創(chuàng)建link標(biāo)簽。

使用 jQuery 創(chuàng)建 link 標(biāo)簽

如果你開發(fā)中喜歡用jQuery,那么用jQuery在創(chuàng)建link標(biāo)簽應(yīng)該是這樣的:

復(fù)制代碼 代碼如下:
var cssURL = '/style.css',
    linkTag = $('<link href="' + cssURL + '" rel="stylesheet" type="text/css" media="' + (media || "all") + '" charset="'+ charset || "utf-8" +'" />');
// 請(qǐng)看清楚,是動(dòng)態(tài)將link標(biāo)簽添加到head里  
$($('head')[0]).append(linkTag);

使用原生 JavaScript 創(chuàng)建 link 標(biāo)簽

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

復(fù)制代碼 代碼如下:
var head = document.getElementsByTagName('head')[0],
    cssURL = '/style.css',
    linkTag = document.createElement('link');
 
    linkTag.id = 'dynamic-style';
 linkTag.href = cssURL;
 linkTag.setAttribute('rel','stylesheet');
 linkTag.setAttribute('media','all');
 linkTag.setAttribute('type','text/css');
 
head.appendChild(linkTag);

IE 里特有的方法 createStyleSheet

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

復(fù)制代碼 代碼如下:
var head = document.getElementsByTagName('head')[0],
    cssURL = 'themes/BlueNight/style.css',
 // document.createStyleSheet 的同時(shí)就已經(jīng)把link標(biāo)簽添加到了head中了,怎么講呢,倒是挺方便
    linkTag = document.createStyleSheet(cssURL);

createStyleSheet( [sURL] [, iIndex])方法接受兩個(gè)參數(shù),sURL就是CSS文件的URL路徑。iIndex 為可選參數(shù),指插入的link在頁(yè)面中stylesheets collection的索引位置,默認(rèn)是在最后添加新創(chuàng)建的樣式。

完整的解決方案

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

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

希望本文所述對(duì)大家的javascript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論