- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>动态应用CSS样式</title>
- <script type="text/javascript">
- 全局变量
- //命名空间
- var lee = {};
- Css文本解析
- /*
- * 将CSS文本转成JSON对象
- * @return json
- */
- lee.cssFormatToJSON = function(cssTxt){
- var s = cssTxt.replace(/[ {}]/g, "");
- var arr = s.split(";");
- var o = {};
- for(var i = 0; i < arr.length; i++){
- if(arr[i].length > 2){
- var arr2 = arr[i].split(':');
- o[arr2[0]] = arr2[1].toString();
- }
- }
- return o;
- };
- lee.cssStyleNameToJsName = function(name){
- if(name == "float")
- return "cssFloat";
- else if(name.indexOf('-') > -1){
- var i = name.indexOf('-');
- return name.substring(0, i) + name.substr(i+1, 1).toUpperCase() + name.substring(i+2);
- }
- else
- return name;
- };
- lee.cssTextToJsNameJSON = function(cssTxt){
- var s = cssTxt.replace(/[ {}]/g, "");
- var arr = s.split(";");
- var o = {};
- for(var i = 0; i < arr.length; i++){
- if(arr[i].length > 2){
- var arr2 = arr[i].split(':');
- var name = lee.cssStyleNameToJsName(arr2[0]);
- o[name] = arr2[1].toString();
- }
- }
- return o;
- };
- 垃圾回收
- lee.gc = function(d){
- var a = d.attributes, i, l, n;
- if(a){
- l = a.length;
- for(i = 0; i < 1; ++i){
- n = a[i].name;
- if(typeof d[n] === 'function'){
- d[n] = null;
- }
- }
- }
- a = d.childNodes;
- if(a){
- l = a.length;
- for(i = 0; i < l; ++i){
- purge(d.childNodes[i]);
- }
- }
- }
- Div类
- function Div(){
- this.div = document.createElement("div");
- }
- Div.prototype.addStyle = function(cssTxt){
- var o = lee.cssTextToJsNameJSON(cssTxt);
- for(var n in o)
- this.div.style[n] = o[n];
- };
- Div.prototype.appendParent = function(parent){
- this.parent = parent;
- this.parent.appendChild(this.div);
- };
- Div.prototype.removeSelf = function(){
- lee.gc(this.div);
- this.parent.removeChild(this.div);
- };
- Div.prototype.addEvent = function(type, func){
- //IE浏览器
- if(this.div.attachEvent)
- this.div.attachEvent("on" + type, func);
- //火狐浏览器
- else if(this.div.addEventListener)
- this.div.addEventListener(type, func, false);
- };
- </script>
- </head>
- <body>
- <script type="text/javascript">
- 测试代码
- var div = new Div();
- //目前还不支持类似于{border:solid 1px red;}这样的结构
- div.addStyle("{position:absolute;left:200px;top:60px;width:100px;height:100px; backgroundColor:#EFEFEF;border-style:solid;border-color:orange;border-width:2px;}");
- div.appendParent(document.body);
- div.addEvent('click', function(){div.removeSelf.apply(div,[]);});
- </script>
- </body>
- </html>
给div动态添加样式
最新推荐文章于 2024-07-11 02:51:24 发布