动态加入Style标签报运行时异常,为什么?
var headId = document.getElementsByTagName("head");var cssNode = document.createElement('style');cssNode.type = "text/css";cssNode.id = "iAddCss";headId.appendChild(cssNode);cssNode.innerText = ".x-form-file-wrap { position: relative; height: 22px; } \n"; 最后一个句报错,不知道为什么,但可加入css文件,代码如下:
var headId = document.getElementsByTagName("head");var cssNode = document.createElement('link');cssNode.type = 'text/css';cssNode.rel = 'stylesheet';cssNode.href = 'http://127.0.0.1:8080/ileU/ploadField.css';headId.appendChild(cssNode);
在网上搜了一下,看到别人是样写的,试了一下可以的,贴出代码来
(IE7测试可以,FF3下不行,报错document.createStyleSheet is not a function ):
var cssNode = document.createStyleSheet();cssNode.addRule(".x-form-file-wrap", "position: relative; height: 22px;");
网上还有这样写说是完美解决,呵呵,但本人测试IE6,FF3下可以, IE7下不行,没有效果,但也不报错
function blue(){ if(document.all){ window.style="body{background-color:blue;"; document.createStyleSheet("javascript:style"); }else{ var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML="body{ background-color:blue }"; document.getElementsByTagName('HEAD').item(0).appendChild(style); }}
总结一下(IE下通用):
使用外部css文件,
var headId = document.getElementsByTagName("head");var cssNode = document.createElement('link');cssNode.type = 'text/css';cssNode.rel = 'stylesheet';cssNode.href = './metadata/tagruler/css/FileUploadField.css';headId.appendChild(cssNode);
不用css文件,直接这样写
//var sheet = document.createStyleSheet();//这样写也可以var sheet = document.styleSheets;sheet.addRule(".x-form-file-wrap", "position: relative; height: 22px;", 0);sheet.addRule(".x-form-file-wrap .x-form-file", "position: absolute; right: 0; "+ "-moz-opacity: 0; filter: alpha(opacity: 0); opacity: 0; z-index: 2; height: 22px;", 1);sheet.addRule(".x-form-file-wrap .x-form-file-btn", "position: absolute; right: 0;z-index: 1;", 2);sheet.addRule(".x-form-file-wrap .x-form-file-text", "position: absolute; left: 0; z-index: 3; color: #777;", 3);
20091106补充:
Ext动态引用CSS文件:
//插入css样式; Ext.util.CSS.swapStyleSheet("DateTimeField", "datetime.css"); 上面这句相当于:
<link id='DateTimeField' rel="stylesheet" type="text/css" href="datetime.css"></link> 查看sqapStyleSheet是这声明的:
swapStyleSheet : function(id, url){ this.removeStyleSheet(id); var ss = doc.createElement("link"); ss.setAttribute("rel", "stylesheet"); ss.setAttribute("type", "text/css"); ss.setAttribute("id", id); ss.setAttribute("href", url); doc.getElementsByTagName("head").appendChild(ss); },
页:
[1]