兼容IE8及以上的IE浏览器
1. [代码][HTML]代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="test"></div>
</body>
<script src="../lib/jquery-1.8.3.min.js"></script>
<script>
/*
* 火狐无 addRule,低版本IE无insertRule,insertRule是w3c标准
* 此处insertRule -> addRule的代码是因为inserterRule只有
*2个参数。2个参数转成3个参数状况比较多
*/
if(!CSSStyleSheet.prototype.insertRule){
CSSStyleSheet.prototype.insertRule = function(style, index){
if(!style){
return;
}
var style = style.split("{");
if(style.length<2){
return;
}
this.addRule(style[0], style[1].split("}")[0], index);
}
}
/*
* 火狐无 removeRule,低版本IE无deleteRule
* delete?Rule是w3c标准音效网
*/http://www.huiyi8.com/yinxiao/?
if(!CSSStyleSheet.prototype.deleteRule){
CSSStyleSheet.prototype.deleteRule = function(index){
this.removeRule(index);
}
}
/**
* 创建一个外部样式表
*/
function sheet(appendTo){
var style = document.createElement("style");
style.type = ‘text/css‘;
appendTo ? appendTo.append(style) : $("body").append(style);
return style.sheet ? style.sheet : style.styleSheet;
}
var sheet = new sheet();
sheet.insertRule("#test{width:100px;height:100px;background:red;border:5px solid green;}", 0);
sheet.insertRule("#test{position:absolute;}", 1);
sheet.insertRule("#test{position:absolute;}", 2);
var mouseDown = false;
var position;
var style;
var target = $("#test");
var x,y;
var rule;
$("#test").mousedown(function(e){
mouseDown = true;
x = e.clientX;
y = e.clientY;
position = target.position();
}).mousemove(function(e){
if(mouseDown == true){
rule = sheet.cssRules ? sheet.cssRules[2] : sheet.rules[2];
rule.style.top = (position.top + e.clientY - y) + "px";
rule.style.left = (position.left + e.clientX - x) + "px";
}
}).mouseup(function(){
mouseDown = false;
});
</script>
</html>
js操作创建和操作外部样式的例子