JavaScript onClick 更改 css

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6176419/
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-08-23 20:33:59  来源:igfitidea点击:

JavaScript onClick change css

javascriptcssonclick

提问by Lenny Magico

This is probably really simple, I know you can change css properties with javascript by doing;

这可能真的很简单,我知道您可以通过以下方式使用 javascript 更改 css 属性;

document.getElementById('bob').style.background='#000000';

But I recently found out that you can do this differently and style multiple things, so something like this;

但我最近发现你可以用不同的方式来做这件事并设计多种风格,所以像这样;

document.getElementById('bob').css='background:#ffffff; color: #000000;';

the problem is I have forgotten what the code, So what I basically want to achieve is what goes in instead of the ".css"? Does anyone know the code I need out the top of their head?

问题是我忘记了代码是什么,所以我基本上想要实现的是什么而不是“.css”?有谁知道我需要的代码?

回答by jAndy

I guess you're looking for the .cssTextproperty from style

我猜你正在寻找.cssText来自style

document.getElementById('bob').style.cssText = 'background:#ffffff; color: #000000;';

Example: http://jsfiddle.net/Sx5yH/

示例:http: //jsfiddle.net/Sx5yH/

回答by Kevin

Have a look at this fiddle: http://jsfiddle.net/YSJfz/

看看这个小提琴:http: //jsfiddle.net/YSJfz/

document.getElementById('myDiv').setAttribute('style', 'background: #f00; color: #fff;');

All I do is change the styleattribute of the element, is that what you meant to accomplish?

我所做的只是改变style元素的属性,这是你想要完成的吗?

回答by Erick Petrucelli

I think what you is looking for is Change an element's class with JavaScript. Since this way you don't need to hardcode all the style changes on the JavaScript itself (which is bad).

我认为您正在寻找的是Change an element's class with JavaScript。由于这种方式,您不需要对 JavaScript 本身的所有样式更改进行硬编码(这很糟糕)。

So you'll have a CSS class like it:

所以你会有一个像这样的 CSS 类:

.myClass {
    background: #ffffff;
    color: #000000;
}

And you'll set to your element like this:

你会像这样设置你的元素:

document.getElementById("MyElement").className += " myClass";

回答by melhosseiny

document.getElementById('bob').style.cssText = 
    'background:#ffffff; color: #000000;';