简体   繁体   中英

jQuery addClass on click to specific element

I am trying to animate a menu item. On move over it expands left, and on mouse out it contracts back. This works fine.

I am also trying to add a class on click to give the button a specific color but it doesn't seem to work.

Here is a fiddle http://jsfiddle.net/g3ra912j/

css:

    #menu1 .active {
        background-color: #00f;
    }

script:

$("#menu1").click(function () {
    $(this).toggleClass("active")
})

onclick it supposed to turn blue, but it doesn't. What am I doing wrong?

Thanks

You have an extra space in your CSS. Should be

#menu1.active {
    background-color: #00f;
}

since you are adding the class .active to the same element as has the id menu1. The original CSS would target an element with class .active inside #menu1.

i had to deal with the same problem. use addClass('active') instead toggleClass. just have an if condition to check if the element already has active class before adding active class

let me know if it works.

and about the css bobdye was right

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