如何在 JavaScript 中编辑 CSS 样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3556619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to edit CSS styles in JavaScript?
提问by Adam
So for example I can do this:
例如,我可以这样做:
document.getElementById('element').onclick = function() {
document.getElementById('element').style.color = '#FFFFFF';
}
But how should I do this?
但是我该怎么做呢?
document.getElementById('element').onclick = function() {
document.getElementById('element').style.-moz-box-shadow = '1px 1px 1px #000';
}
I hope you get what I mean :)
我希望你明白我的意思:)
Please do not post any answer related with jQuery or any library, I want it in plain javascript.
请不要发布任何与 jQuery 或任何库相关的答案,我想要它在纯 javascript 中。
回答by jvenema
I believe it's:
我相信是:
myobject.MozBoxShadow = '1px 1px 1px #000';
It doesn't follow the "typical" formatting of a style object (which would lower-case the "M") because of the initial "-" character. Converting between style properties and JS properties for those styles means:
由于初始的“-”字符,它不遵循样式对象的“典型”格式(将小写“M”)。在这些样式的样式属性和 JS 属性之间进行转换意味着:
- Converting the first character to lower case
- Converting all characters after dashes to upper case
- Removing all dashes
- 将第一个字符转换为小写
- 将破折号后的所有字符转换为大写
- 删除所有破折号
Thus, "-moz-box-shadow" becomes:
因此,“-moz-box-shadow”变成:
- -moz-box-shadow (the first character is a "-", so it doesn't have a lower case)
- -Moz-Box-Shadow
- MozBoxShadow
- -moz-box-shadow (第一个字符是“-”,所以它没有小写)
- -Moz-Box-Shadow
- 魔盒阴影
回答by cofiem
I think you change '-' to a capital letter, so:
我认为您将“-”更改为大写字母,因此:
document.getElementById('element').style.-moz-box-shadow = 1px 1px 1px #000;
Should be:
应该:
document.getElementById('element').style.MozBoxShadow = "1px 1px 1px #000";

