How can you change the attached CSS file with Javascript?

前端 未结 4 413
囚心锁ツ
囚心锁ツ 2021-01-03 06:34

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

For example:



        
相关标签:
4条回答
  • 2021-01-03 06:40

    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

    0 讨论(0)
  • 2021-01-03 06:52

    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>
    
    0 讨论(0)
  • 2021-01-03 06:55

    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>
    
    0 讨论(0)
  • 2021-01-03 06:55

    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.

    0 讨论(0)
提交回复
热议问题