如何通过javascript改变css类风格? [英] how to change a css class style through javascript?

查看:105
本文介绍了如何通过javascript改变css类风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我正在阅读的书,最好是改变CSS,当你使用javascript来改变CSS。但如何?

according to the book that I am reading, it is better to change a css, by class when you are using javascript for changing css. but how? can someone give a sample snippet for this ?

推荐答案

假设你有:

<div id="mydiv" class="oldclass">text</div>

和以下样式:

.oldclass { color: blue }
.newclass { background-color: yellow }

您可以在javascript中更改 mydiv 中的类:

You can change the class on mydiv in javascript like this:

document.getElementById('mydiv').className = 'newclass';

DOM操作后,您将看到:

After the DOM manipulation you will be left with:

<div id="mydiv" class="newclass">text</div>

如果要添加新的css类而不删除旧的css类,可以附加:

If you want to add a new css class without removing the old one, you can append to it:

document.getElementById('mydiv').className += ' newClass';

这将导致:

<div id="mydiv" class="oldclass newclass">text</div>

这篇关于如何通过javascript改变css类风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆