简体   繁体   中英

Changing CSS attribute using toggleClass() on an input button

I have a red button, and I'd like to change it to a white button with a red outline when clicked, and then back to full red when clicked again. I cannot get it to change when clicked. It just stays red.

I'd like to be able to use "toggleClass()", the jquery function, to apply a class to the button with custom (background color) attributes. It uses the ".buttonF" CSS attribute, but will not apply the ".off" CSS attribute, as it would appear the class is not getting turned on by "toggleClass()"

The button toggles text appearing on the page, but that's not relevant to my issue.

Here is my HTML page:

<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="ryft1.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<head></head>

<script>

function toggleF(button){
    $(this).toggleClass("off"); <!-- Toggle background color by changing class-->

    var f = document.getElementsByClassName("key");
    var i;

    if(document.getElementById("1").name=="OFF"){
        document.getElementById("1").name="ON";
        for(i=0; i<f.length; i++){
            f[i].style.display="block";
        }       
    }

    else if(document.getElementById("1").name=="ON"){
        document.getElementById("1").name="OFF";
        for(i=0; i<f.length; i++){
        f[i].style.display="none";
        }
    }
}

</script>

<body>
<form action="">

<input type="button" class="buttonF" id="1" value="F"
       onclick="toggleF(this);" name="ON">

<p class="key">Sample text</p>

</body>
</html>

Here is my CSS page:

.buttonF {
    background-color: #ff0000;
    padding: 13px 15px;
    text-align:center;
    font-size: 12px;
    border-radius: 50%;
    border: 2px solid #ff0000;
}

.off{
    background-color: #ffffff
}

You need to select the button in your function. this is not pointing to the element, but to the window object. Your element's this is the argument from your function.

Change this line:

$(this).toggleClass("off");

To this:

$(button).toggleClass("off");

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