Overwrite a css rule using javascript or jquery
Is it possible to overwrite a css rule using jquery or javascript?
Let's say I have a table, with a bunch of rows, and each row holds a specific type of data. Each row (tr) has a class added to it, so we can differentiate between the data types it is holding.
For this example let's say the rows, with class "names" holds information about persons, and the rows with class "company" hold information about companies.
Let's say that we have a filter above our table, where we can hide and show all companies or persons from our table. When we select a checkbox, we either change the display of the specific rows to none, or to block(depending on the checkbox state), OR we add a class (hidden) to our specific rows. Our css would look something like this:
.names {
/*additional css stuff here*/
}
.company {
/*additional css stuff here*/
}
.company .hidden {
display: none;
}
.names .hidden {
display: none;
}
This works just fine, but what if I, say hide all the names, by adding the hidden class to the specific rows, but later introduce dynamically a new record of a person to the database. I would have to check our checkboxes state, and apply (or ommit) the specific class to the new tr, before inserting it to our table structure.
If I could somehow overwrite a css rule dynamically, for example, when the "names" checkbox gets checked, I overwrite the ".names" class from CSS, to display: none, I wouldn't have to worry about making additional checks when inserting new data in the table.
Is this possible somehow?
EDIT: I know how I can dynamically add a new class, or remove a class from a html element. What I want to achieve is to change the stylesheet on the run with jquery, overwrite the rules of a specific class from the original stylesheet.
You should not change a stylesheet rule. Instead change where you are adding classes to control the display state. Add a class to the table (or tbody) and not the rows.
Example: you want company rows hidden, you add a class "companyHidden" to the table element. The following rule will hide those rows.
table.companyHidden tr.company {
display: none;
}
This way you do not have to worry about new rows and CSS does the work for you.
You can add a style element, with the required CSS, on the fly to the document body.
See this JSFiddle
If references bootstrap.css and, on load, overrides .btn-primary:
$(function(){
$("<style>")
.text(".btn-primary{ background-color: cyan !important; min-height:20px; }")
.appendTo($("body"));
});
You could use a similar approach I think?
链接地址: http://www.djcxy.com/p/94876.html