Dynamically load and unload stylesheets

前端 未结 3 381
-上瘾入骨i
-上瘾入骨i 2020-12-29 08:33

I\'ve searched various posts and forums but can\'t find the right answer. I need to find a way to dynamically load and unload stylesheets.

I\'m building a website th

3条回答
  •  甜味超标
    2020-12-29 09:11

    To Load css dynamically

    var headID = document.getElementsByTagName("head")[0];
    var cssNode = document.createElement('link');
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    cssNode.href = 'FireFox.css';
    cssNode.media = 'screen';
    headID.appendChild(cssNode);
    

    To Unload css file

    function removefile(filename, filetype) {
    var targetElement = "link"; 
    var targetAttr = "href"; 
    
    var allCtrl = document.getElementsByTagName(targetElement);
    for (var i=allCtrl.length; i>=0; i--)  { //search backwards within nodelist for matching elements to remove
    if (allCtrl[i] && allCtrl[i].getAttribute(targetAttr)!=null && allCtrl[i].getAttribute(targetAttr).indexOf(filename)!=-1);
    allCtrl[i].parentNode.removeChild(allCtrl[i]);
    }
    }
    

提交回复
热议问题