Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

stylesheet - 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;
     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...