使用 JavaScript 更改按钮的 CSS 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13698025/
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
Change CSS Class of Button Using JavaScript
提问by user1822824
Is it possible to change the CSS class of an HTML button using JavaScript?
是否可以使用 JavaScript 更改 HTML 按钮的 CSS 类?
I tried this but it didn't work:
我试过这个,但没有用:
document.getElementById("btnChoice1").setAttribute("class", "redButton");
HTML Button
HTML 按钮
<button class="basicButton" id="btnChoice1">
CSS
CSS
.basicButton {
width:300px;
}
.redButton {
width:300px;
background-color:red;
}
回答by sevenseacat
Try document.getElementById("btnChoice1").className = 'redButton'
.
试试document.getElementById("btnChoice1").className = 'redButton'
。
回答by MrCode
className
is preferred but your setAttribute()
code should work. If it's not working then you probably have the Javascript executing before the button exists on the page.
className
是首选,但您的setAttribute()
代码应该可以工作。如果它不起作用,那么您可能在页面上存在按钮之前执行了 Javascript。
Check that the code is within an window.onload
event or is after the button markup.
检查代码是否在window.onload
事件内或在按钮标记之后。
回答by Knerd
you could try it with this code:
你可以用这个代码试试:
document.getElementById("btnChoice1").className = "redButton";
if you want to use jquery you have to write it like this:
如果你想使用 jquery,你必须这样写:
(document.getElementById("btnChoice1")).setAttribute("class", "redButton");
Greets Knerd
问候克纳德
回答by Udan
Your code works.
您的代码有效。
You probbably didn't put the javascript where it should be or you have some error in your code so javascript doesn't execute.
您可能没有将 javascript 放在应有的位置,或者您的代码中有一些错误,因此 javascript 无法执行。
<button id="change" onClick="document.getElementById('btnChoice1').setAttribute('class', 'redButton');">change</button>
<button class="basicButton" id="btnChoice1">
test
</button>
?
?
Proof that your code is working here http://jsfiddle.net/nDmKP/
证明您的代码在这里工作http://jsfiddle.net/nDmKP/