动态添加删除css/js文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <div class="a">动态改变字体样式</div>
        <button onclick="addCss('./css/a.css')">添加css文件</button>
        <button onclick="removejscssfile('./css/a.css','css')">删除css文件</button>
        <button onclick="addjs('./js/b.js')">添加js文件</button>
        <button onclick="removejscssfile('./js/b.js','js')">删除js文件</button>
    </div>
    <script>
        //动态添加css样式文件
        function addCss(cssUrl){
            var linkObj = document.createElement("link");
            linkObj.setAttribute("href",cssUrl);
            linkObj.setAttribute("rel","stylesheet");
            document.body.appendChild(linkObj);
        }
        //动态添加js文件
        function addjs(jsUrl){
            var linkObj = document.createElement("script");
            linkObj.setAttribute("src",jsUrl);
            document.body.appendChild(linkObj);
        }
       //删除js/css文件
        function removejscssfile(filename,type){
            var targetelement;
            var targetattr
            if(type == 'css')
            {
                targetelement = 'link';
                targetattr = 'href';
            }
            else
            {
                targetelement = 'script';
                targetattr = 'src';
            }

            var allsuspects=document.getElementsByTagName(targetelement);

            for (var i=allsuspects.length-1; i>=0; i--)
            {
                if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1){
                    allsuspects[i].parentNode.removeChild(allsuspects[i]);
                }  
            }
        }
    </script>
</body>
</html>

你可能感兴趣的:(js)