0

I have, for example, this CSS rules:

<style>
table {background:red;}
div {background:green;}
</style>

and the following HTML, calling a JS function:

<table onclick="turnItsCSS(on/off)"><tr><td>123</td></tr></table>

Is it possible for turnItsCSS() to toggle CSS rules for tables?

All I figured is to parse innerHTML in document head, but it doesn't seem to be sufficient.

4

4 回答 4

0

In jQuery you can use the .addClass() or .removeClass() (or more simply, the .toggleClass() function)

So, say you have a table:

<a href="#" id="addClass">Add CSS</a>
<table id="the_table">
    <tr>
        <td>Hello, World</td>
    </tr>
</table>

And you have the following CSS:

.table_red {
    color: red;
}

In your jQuery, you could have:

$("#addClass").click(function() {
    $("#the_table").addClass(".table_red");

    // Check if the class is active, and remove it for a toggle.
    // or use the .toggleClass() function.
});
于 2013-02-12T00:11:29.323 回答
0

这是在 css 文件之间切换的好方法:

<button onclick="$('[rel=stylesheet]').attr('href','http://www.example.com/css/menu_red.css')">red</button>

<button onclick="$('[rel=stylesheet]').attr('href','http://www.example.com/css/menu_black.css')">black</button>
于 2013-02-12T00:17:41.917 回答
0

您可以使用 jQuery 或 JavaScript 在 JavaScript 中动态更改对象样式您可以通过 id 或类名获取元素并设置样式

var obj = getElementById("idName");
obj.style.width = "300px";

或者

var obj = getElementsByClassName("classname")[0]; //return array with with all elements with same class
obj.style.width = "300px";
于 2013-02-12T00:25:04.930 回答
0

这是一个使用 HTML5 的示例,不幸的是,我认为 < IE10 不支持它。

HTML

<table onclick="this.classList.toggle('on');"><tr><td>123</td></tr></table>

CSS

.on { 
    background-color:red;
}

http://jsfiddle.net/sGKgV/

查看https://stackoverflow.com/a/196038/1156119以全面了解其他技术。

于 2013-02-12T00:25:53.710 回答