简体   繁体   中英

How to change css classes with a button click in javascript?

I'm confused on what I'm doing wrong here I'm following a tutorial and it works fine for them but not me. I've switched around many things to try to find the problem but it just doesn't seem to work.

HTML

<h1 class="settingOne" id="mainText">Simple HTML Page</h1>
    <p class="center">
        This is a very simple HTML page.
    </p>

    <p class="center">It's about as basic as they come. It has: </p>

    <ul class="center">
        <li>An H1 Tag</li>
        <li>Two paragraphs</li>
        <li>An unordered list</li>
    </ul>

    <button id="changeButton">
        <p>
            Hey push this to change the header thing
        </p>
    </button>

CSS

.settingOne {
    font-family: fantasy;
    color: blue;
    text-align: center;
}

.settingTwo {
    font-family: serif;
    color: red;
    text-align: center;
}

JAVASCRIPT

function changeClass() {
    document.getElementById("changeButton").onclick = function () {
        if (document.getElementById("mainText").className === "settingOne") {
            document.getElementById("mainText").className = "settingTwo";
        } else {
            document.getElementById("mainText").className === "settingOne";
        }
    };
}

window.onload = function () {
    preparePage();
}

;

In the Javascript, the line

else { document.getElementById("mainText").className === "settingOne"; }    

should be changed to

else { document.getElementById("mainText").className = "settingOne"; }    

The single = is used to set one thing equal to another, which is the behavior you want here.

Working example: https://jsfiddle.net/w6no44v1/20/

It's not clear if your changeClass function is ever called. I provide an example that cleans up your code a bit by storing the first query to the element changeButton in the variable ele and then registering the click handler when the window.onload event occurs. You could of course wrap this all up in another function called registerHandlers or put it in your preparePage function instead.

window.onload = function () {
    var ele = document.getElementById("changeButton");
    ele.onclick = function() {
        if(ele.className === "settingOne") {
            ele.className = "settingTwo";
        } else {
            ele.className = "settingOne";
        }
    };
};

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