jQuery包括css

如何在添加css样式,放在javascript文件中,如下所示:

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

唯一的方法是在javascript中编写css,无法访问html或任何外部CSS。

谢谢。

使用jquery的addClass方法:

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

更新:

  $(function(){ $('head').append('  '); }); 

如果在您的结构/标记中使用类定义类,则:

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

或者将其添加到特定标记:

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

并注入它:

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

您可以创建

元素,将它们添加到文档中,然后使用

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

管他呢。

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

如果你愿意,你可以将你的风格块添加到头部。

编辑 - 多行样式块:

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

您还可以使用一个向主体添加类的函数,这意味着该页面中的所有css都可以检测到该类

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

在标题或.css文件中,您可以在javascript中没有css样式的情况下引用更改。

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

由于保证只有一个body元素,因此选择元素本身是有效的。

你可以使用类似$('body').addClass('popup-bg');东西$('body').addClass('popup-bg');