简体   繁体   English

Javascript:通过.style在鼠标悬停时设置元素颜色

[英]Javascript: Set an elements color on hover through .style

I am writting CSS dynamically in Javascript. 我正在用Javascript动态编写CSS。 I am trying to specify(in Javscript) that when the mouse hovers over a paragraph element its text colour changes. 我试图指定(在Javscript中)当鼠标悬停在段落元素上时,其文本颜色会更改。

Is there a way to do this without having to resort to the onMouseOver way, something like... 有没有一种方法可以不必诉诸onMouseOver方式,例如...

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. 只需将您的文本包装在附加的A标记中,然后使用:hover即可更改文本的颜色。

Of course you'll probably want to create a class and add it via JavaScript. 当然,您可能想要创建一个类并通过JavaScript添加它。

JavaScript: JavaScript:

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

CSS: CSS:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM