简体   繁体   中英

How can you change the attached CSS file with Javascript?

I was wondering, is it possible to change the attached stylesheet using JavaScript?

For example:

<link href="stylesheet.css" rel="stylesheet" type="text/css">
.....
<div id="controls">
    <div id="red" onClick="styler(1)">R</div>
    <div id="green" onClick="styler(2)">G</div>
    <div id="blue" onClick="styler(3)">B</div>
    <div id="reset" onClick="styler(4)">Reset</div>
</div>

JavaScript

function styler(attr){
    switch(attr){
         case'1':document.----- = "stylesheet1.css";break;
         case'2':document.----- = "stylesheet2.css";break;
         case'3':document.----- = "stylesheet3.css";break;
         case'4':document.----- = "stylesheet.css";break;
         default:;break;
     }
}

Add an id to the link tag and use

<link id="myStyleSheet" href="stylesheet.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
    function styler(attr){
        var href;
        switch(attr){
            case'1':href = "stylesheet1.css";break;
            case'2':href = "stylesheet2.css";break;
            case'3':href = "stylesheet3.css";break;
            case'4':href = "stylesheet.css";break;
            default:;break;
        }
        document.getElementById('myStyleSheet').href = href;
    }
</script>

See this post

It should be easy:

<html>
<head>
    <link rel="stylesheet" href="/tmp/default.css" id="default">
</head>

<body>
<button id="bt">change style</button>

<script>
    var targetStyle = document.querySelector('#default'),
        otherStyle = '/tmp/style2.css';

    document.querySelector('#bt').onclick = function(){
        targetStyle.href=otherStyle;        
    };

</script>

</body>
</html>

Try it

 <!DOCTYPE html>
    <html>
    <head>
    <link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
    <script>
    function swapStyleSheet(sheet){
        document.getElementById('pagestyle').setAttribute('href', sheet);
    }
    </script>
    </head>
    <body>
    <h2>Javascript Change StyleSheet Without Page Reload</h2>
    <button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
    <button onclick="swapStyleSheet('blue.css')">Blue Style Sheet</button>
    <button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>
    </body>
    </html>

Another option is to toggle the disabled property of the link DOM element. According to Mozilla the disabled HTML attribute is non-standard, but the javascript property is . So if you're toggling it with JS you should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM