Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I got this HTML code:

<head>
    <script type="application/javascript" src="javascript.js">
    <link id="pagestyle" href="default.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <button id="stylesheet1" > Default Style Sheet </button>
    <button id="stylesheet2" > Dark Style Sheet </button>
</body>

And in javascript.js I got this:

function swapStyleSheet(sheet) {
    document.getElementById("pagestyle").setAttribute("href", sheet);  
}

function initate() {
    var style1 = document.getElementById("stylesheet1");
    var style2 = document.getElementById("stylesheet2");

    style1.onclick = swapStyleSheet("default".css);
    style2.onclick = swapStyleSheet("dark".css);
}

window.onload = initate;

I want to the style sheets to change while pressing this buttons. I can't figure out why it is not working.

See Question&Answers more detail:os

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

1 Answer

One guess would be the missing .css property, another would be the fact that onclick is not a function, but a result from invoking one:

Make all of .css a string and assign functions to onclick:

style1.onclick = function () { swapStyleSheet("default.css") };
style2.onclick = function () { swapStyleSheet("dark.css"); };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...