简体   繁体   中英

Javascript: Set an elements color on hover through .style

I am writting CSS dynamically in Javascript. I am trying to specify(in Javscript) that when the mouse hovers over a paragraph element its text colour changes.

Is there a way to do this without having to resort to the onMouseOver way, something like...

myEle.style.colorHover = "#FFFFFF";

// Maybe this works?
var ele = document.createElement("p");
ele.style.colorHover = "#FFFFFF";
ele.style.backgroundColorHover = "#000000";
ele.style.color = "#000000";
ele.style.backgroundColor = "#FFFFFF";

Just wrap your text in an additional A tag and use :hover to change the color of your text.

Of course you'll probably want to create a class and add it via JavaScript.

JavaScript:

ele.setAttribute("class", "myClass");

CSS:

P A.myClass
{
 /* colors when not hovering */   
}
P A.myClass:hover
{
 /* colors when hovering */
}

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