开发者

jQuery include css

How to add css styles inside <body> or <head>, placed in javascript file like this:

<style type="text/css">
    .popup-bg {
        position: fixed;
        left: 0;
        top: 0;
        width: 100开发者_运维百科%;
        height: 100%;
        background: #eee;
    }
</style>

The only way is to write css inside javascript, there is no access to html or any external css.

Thanks.


IF the class is defined in your structure/markup with the class then:

$(".popup-bg").css({ position: fixed, 
        left: 0, 
        top: 0, 
        width: 100%, 
        height: 100%, 
        background: #eee 
 });

OR to add it to a particular tag:

    $("body").css({ position: fixed,  
            left: 0,  
            top: 0,  
            width: 100%,  
            height: 100%,  
            background: #eee  
     });

AND to inject it:

var style = document.createElement('style'); 

style.innerText = '.popup-bg{ position: fixed,  
            left: 0,  
            top: 0,  
            width: 100%,  
            height: 100%,  
            background: #eee  
     }'; 

document.head.appendChild(style); 


Use addClass method of jquery:

$('body').addClass('popup-bg');

Update:

  $(function(){
    $('head').append('
      <style type="text/css">
        .popup-bg {
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: #eee;
        }
      </style>
    ');
  });


You can create <style> elements, add them to the document, and then use

 $('#styleId').text('.something { display: none; }');

or whatever.

 $('body').append($('<style/>').attr("id", "myNewStyle"));
 $('#myNewStyle').text('.something { whatever: 10px; }');

You could append your style blocks to the head, if you wanted to.

edit — multi-line style block:

 $('#myNewStyle').text(
 ' .something { ' +
 '    font-size: 12px; ' +
 '    font-weight: normal; ' +
 '    color: #e0f0e0; ' +
 ' }'
 );


You can also have a function that adds a class to the body which means all css in that page can detect that class

if (device.platform == "iPhone" || device.platform == "iPhone Simulator")
{
     $("body").addClass('iPhone');
}

In the header or in .css file you can reference the change without having css styles in javascript.

<style type="text/css">
    body.iPhone .popup-bg {
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: #eee;
    }
</style>


$('body').addClass('popup-bg');

Since there is guaranteed to be only one body element, selecting on the element itself works.


You can use something like $('body').addClass('popup-bg');

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜