简体   繁体   中英

How to change CSS pseudo-class element using JavaScript

I want to change this image using javascript:

 dance:active { background-image: url("myImage.png") }

You can use

document.getElementById(element).style.backgroundImage = url(image);

to change

#element {background-image: url(image)}

I would like to change the image of when the element is active using javascript. Thanks!

I figured it out!

You can have multiple classes in your CSS :

element.dance1 { stuff }
element.dance1:active { active stuff }
element.dance2 { stuff 2 }
element.dance2:active { active stuff 2 }

and then change the class of the element in javascript:

document.getElementById(element).className = dance1/dance2

You can try using jQuery to achive what you want. dance: active is CSS Pseudo-classes. Learn more about Pseudo-class .

The demo change the div color when mouse down and switch the color back when mouse up. Leave comments if this is not what you want.

$("#dance").on("mousedown", function () {
    $("#dance").css("background", "blue");
}).on("mouseup", function(){
    $("#dance").css("background", "black");
});

https://jsfiddle.net/x_li/5nkvms8q/

and jQuery can also do the following

$('#damce:checked').val();

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