简体   繁体   English

用javascript改变divs css

[英]alter divs css with javascript

Can I change style of some div link. 我可以改变一些div链接的样式。 Here is what I mean 这就是我的意思

<div id="somediv"><a href="#">something</a>/div>

Lets say I have css like this : 让我们说我有这样的CSS:

#somediv a{
color:#000;
}

Now for instance upon some action such as mouse click on any element I want to change somediv a link css to 现在举个例如鼠标点击任何元素的一些动作我想改变一些链接css到

#somediv a{
color:#00ffff;
}

I know how to select div, by using Document.get.elementById('somediv') 我知道如何使用Document.get.elementById('somediv')选择div
Is it possible to select a by using above method or any other? 是否可以通过使用上述方法或任何其他方法来选择?

Thank you 谢谢

DETAILS: Yes I know how to select it using jquery, or prototype .. I can't use any of those.. DETAILS:是的我知道如何使用jquery或原型选择它..我不能使用任何这些..

If you just want to apply a style to a particular element, it's very easy to do: 如果您只想将样式应用于特定元素,则可以很容易地执行:

document.getElementById('whatever').style.color = '#f0f';

If you actually want to apply cascading styles (eg: #someDiv a ), then it's not so easy (though it is definitely possible). 如果你真的想要应用级联样式(例如: #someDiv a ),那么它就不那么容易了(尽管它绝对可能)。 I would suggest applying a new class to something, and having a pre-existing rule in your CSS. 我建议将新类应用于某些内容,并在CSS中使用预先存在的规则。

CSS: CSS:

#someDiv a {
    color: #000;
}
#someDiv.awesome a {
    color: #f0f;
}

Javascript: 使用Javascript:

document.getElementById('someDiv').className = "awesome";

Yep, you can modify the actual CSS rules at runtime. 是的,您可以在运行时修改实际的CSS规则。 See Totally Pwn CSS with Javascript for more details. 有关详细信息,请参阅使用Javascript的Totally Pwn CSS

If you're using jQuery or YUI, there's some good info in question 1079237 如果你正在使用jQuery或YUI,那么问题1079237就会有一些很好的信息

document.getElementById ( 'somediv' ).children[0].style.color = 'new color';

假设A标签将是DIV中的第一个元素

You could use CSS behaviors for this: 你可以使用CSS行为:

For instance: 例如:

#somediv a:hover
{
    color:#0ff;
}

Otherwise, you may create a dedicated class (used when an element is click for example): 否则,您可以创建一个专用类(例如,在单击元素时使用):

#onclickclass
{
    color:#0ff;
}

Then in JavaScript, on onClick event, do: 然后在JavaScript中,在onClick事件上,执行:

document.getElementById('somediv').className = 'onclickclass';

并改变风格使用

document.getElementById('somediv').className = 'your-css-class';

If you really want to select the anchor you would have to then traverse the document.getElementById('somediv').children array. 如果你真的想选择锚,那么你必须遍历document.getElementById('somediv').children array。

As others have suggested though the simpler answer would be to set the className attribute on your div and let the CSS style cascade onto the anchor tag. 正如其他人所建议的那样,更简单的答案是在div上设置className属性,让CSS样式级联到锚标记上。

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

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