javascript创建css样式

1:

var style = document.createElement(’link’); 
style.href = ’style.css’; 
style.rel = ’stylesheet’; 
style.type = ‘text/css’; 
document.getElementsByTagName(’HEAD’).item(0).appendChild(style);

2:

document.createStyleSheet().cssText = '标签{color:red;' +
// 这个注释只在当前JS中帮助理解,并不会写入CSS中
'300px;height:150px}' +
'.类名{……}' +
'#ID们{……}'
;

3;

完善一点的方法,防止重复添加,可以通过添加样式表ID并对其判断来实现:

if (!document.styleSheets['要建立的样式表ID如theforever']) { //先检查要建立的样式表ID是否存在,防止重复添加
var ss = document.createStyleSheet();
ss.owningElement.id = '要建立的样式表ID如theforever';
ss.cssText = '标签{display:inline-block;overflow:hidden;' +
// 这个注释只在当前JS中帮助理解,并不会写入CSS中
'text-align:left;300px;height:150px}' +
'.类名{……}' +
'#ID们{……}'
;
}

document.styleSheets:Returns a list of stylesheet objects for stylesheets explicitly linked into or embedded in a document.

The createStyleSheet method is only supported by Internet Explorer. In other browsers, use the createElement method to create a new link orstyle element, and the insertBefore or appendChild method to insert it into the document. See the examples below for details.

document.createStyleSheet('styles.css');
http://msdn.microsoft.com/en-us/library/ie/ms531194(v=vs.85).aspx
原文地址:https://www.cnblogs.com/youxin/p/2957430.html