I'm want to create a style element after loading of page ( say about 2-3 sec after page loaded )
html
<html>
<body>
<div id="div1" >
<div id= "div2" > some text goes here </div>
</div>
</body>
</html>
javascript
$(function () {
var style = $('<style type="text/css" />').appendTo('head');
style.html('body{ background:#000; }
\n
\#div1{ background:#0099f9; }'
//I'm having some more elements which I need to alter their style attr's
);
var attr = style.html;
style.html(attr + '\n\#div2{ background:#f0f; }');
});
I'm also having a bunch of html elements ( some more elements other than mentioned ) in which I need to change their styles after the page loaded
I feel the difficulty when I try to read my code because it is hard coded,
I'm also facing the problem, when I need to add some elements to the above style tag
Is their simple way to do 开发者_开发技巧this & make it simple for readability
Thanks for help !!
Have a Good Day
I don't know if this could help you but rather then dynamically trying to write CSS, can't you create the different styles and give your elements the correct CSS class when rendering them?
Like this:
div.even
{
background-color:#f00;
}
div.odd
{
background-color:#ff0;
}
Then you can determine the correct CSS class server side (with PHP, ASP.Net, ...) when rendering the page.
I suggest looking into a client-side template system, like the mechanism discussed here: http://blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/
That approach would let you keep your CSS fragments separate from the code, which would be a lot cleaner. You'd put your CSS into <script>
blocks that have a "type" deliberately made so that the browser won't try to execute them.
精彩评论