如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:30:37  来源:igfitidea点击:

How to edit CSS styles in JavaScript?

javascriptcss

提问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 属性之间进行转换意味着:

  1. Converting the first character to lower case
  2. Converting all characters after dashes to upper case
  3. Removing all dashes
  1. 将第一个字符转换为小写
  2. 将破折号后的所有字符转换为大写
  3. 删除所有破折号

Thus, "-moz-box-shadow" becomes:

因此,“-moz-box-shadow”变成:

  1. -moz-box-shadow (the first character is a "-", so it doesn't have a lower case)
  2. -Moz-Box-Shadow
  3. MozBoxShadow
  1. -moz-box-shadow (第一个字符是“-”,所以它没有小写)
  2. -Moz-Box-Shadow
  3. 魔盒阴影

回答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";