jQuery动态创建样式元素 [英] jQuery Creating a style element on fly

查看:57
本文介绍了jQuery动态创建样式元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在页面加载后创建一个样式元素(例如,页面加载后约2-3秒)

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; }');
});

我还有一堆html元素(除了提到的元素之外的其他元素),在页面加载后我需要在其中更改样式

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

感谢帮助!

祝你有美好的一天

推荐答案

我不知道这是否对您有帮助,而是动态地尝试编写CSS,您能否创建不同的样式并为您的元素提供正确的样式呈现它们时使用CSS类吗?

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?

赞:

div.even
{
  background-color:#f00;
}

div.odd
{
  background-color:#ff0;
}

然后,您可以在呈现页面时确定正确的CSS类服务器端(使用PHP,ASP.Net等).

Then you can determine the correct CSS class server side (with PHP, ASP.Net, ...) when rendering the page.

这篇关于jQuery动态创建样式元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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