开发者

How to temporarily add a CSS style?

I have a div and when I mouse over it I want to change the background (and possibly other properties). I can do it by calling el.style.backcolor = "", but is there a way I can add another CSS style to it then remove it later? Like style += mouseOverStyle and then style -= mouseOverStyle. That way I could select the properties to change in the CSS instead of in the JavaScript code.

EDIT: I may want to apply the new style in other situations, not just mouseover, so #div:hover isn't really a general solution. What I'm really asking is is there something like开发者_开发技巧 style.add("style") and style.remove("style")?


If I understood you correctly, you're asking to change the background when you hover your div element?

This is easily done via CSS, no Javascript or other codes are necessary!

#myDiv
{
   background-color: #f00;
}

#myDiv:hover
{
   background-color: #00f;
}

Of course you can change other styles too, you don't need to add another class to change one or more styles.

Hope that helps :)


Just add or remove CSS classes when needed.

Adding:

yourElement.className += ' my_class';

Removing:

yourElement.className = yourElement.className.replace(/\bmy_class\b/, '');

With jQuery you can use addClass, removeClass and toggleClass methods (see the docs).


You could try using multiple :hover pseudo selectors:

div.style1:hover { background: red }
div.style2:hover { background: yellow }

Then use javascript/jquery to switch between html class attributes


I would recomendate you to use a JS library, such as jQuery. In jQuery it is simple like that: http://api.jquery.com/addClass/ together with the mouseover event handling http://api.jquery.com/mouseover/.


function changeStyle()
{
   document.getElementById("elementID").style.color="green";
 }

after the .style. you should paste the css attribute you want to edit.


If you're wanting to use js, change the properties on the user event.

onmouseover : el.style.background = "blue";

onmouseout : el.style.background = "red";

If you want to add more properties as time goes along just throw it in a function

function onMouseOverFunction () {
   el.style.background = "blue";
   el.style.color = "blue";
   el.style.font-size= "1em";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜