Dynamically load stylesheets

后端 未结 3 674
慢半拍i
慢半拍i 2021-01-02 14:03

i know that you can have style-sheets in the head of a page, but i like to have them in a separate file. Now i\'m working with a single page application.

Well in an

3条回答
  •  一个人的身影
    2021-01-02 14:51

    You can add/remove/edit link tags in your head area with java script to add/remove stylesheet files.

    Code example:

    Add a stylesheet to the head:

    var newstyle = document.createElement("link"); // Create a new link Tag
    // Set some attributes:
    newstyle.setAttribute("rel", "stylesheet");
    newstyle.setAttribute("type", "text/css");
    newstyle.setAttribute("href", "filename.css"); // Your .css File
    document.getElementsByTagName("head")[0].appendChild(newstyle);
    

    To remove or edit a stylesheet you can give every stylesheet an id attribute and access it with this:

    document.getElementById('styleid')
    

    Or you can loop through all link tags in the head area and find the correct one but I suggest the solution with the ID ;)

    Now you can change the href attribute:

    document.getElementById('styleid').setAttribute("href", "newfilename.css");
    

    Or you can remove the complete tag:

    var styletorem = document.getElementById('styleid');
    styletorem.parentNode.removeChild(styletorem)
    

提交回复
热议问题