2012-04-25 65 views
3

在我的web应用的方法之一,我动态创建HTML元素和使用此代码添加一个动态进行的CSS对象:Jquery的CSS功能犯规使用所有参数在地图

tag = typeof(tag) !== 'undefined' ? tag : "div"; 
    end = typeof(end) !== 'undefined' ? end : true; 
    var html = '<'+tag+' value="'+this.id+'" class="element '+this.type+'"'+ 
       'style="position:absolute;z-index= '+this.id+'"' 
    end ? html += "></"+tag+">" : html += "/>"; 
    var css = {},element = this; 
    $.each(this.properties(),function(){ 
     var hash=this.indexOf("Color") !== -1?'#':''; 
     var property = typeof(element[this])==='number'?element[this]*Nx.ratio:element[this]; 
     css[this]=hash+property; 
    }) 
    console.log(css); 
    html = $(html).css(css); 
    $('.page[value='+page+']').append(html); 

这里是CSS的一个例子所创建并传递给CSS()函数从我的console.log采取对象:

Object 
backgroundColor: "#ff0000" 
borderColor: "#ffffff" 
borderStyle: "solid" 
borderWidth: "0" 
height: "56.865" 
left: "0" 
top: "274.29" 
width: "893.115" 
__proto__: Object 

现在的问题是,作为输出元件不必须顶部,左侧,高度和宽度的性能,例如:

<div value="12" class="element rectangle" style="position: absolute; background-color: rgb(255, 0, 0); left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-top-color: rgb(255, 255, 255); border-right-color: rgb(255, 255, 255); border-bottom-color: rgb(255, 255, 255); border-left-color: rgb(255, 255, 255); border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; "></div> 

回答

2

这些CSS属性不适用于您的元素,因为您没有正确指定它们。的lefttopwidthheight的值必须是:

  • 一个数字,如0274.29
  • 或字符串后跟一个单元后缀,如"0px""274.29px"

您的代码使用没有单位后缀的字符串,因此这些值被认为是无效的,并且属性被忽略。

2

你的代码看起来莫名其妙问题......真的不能告诉错误所在,但你在这里失去了;

...'style="position:absolute;z-index= '+this.id+'"'; <-- there! 

而且这样的:

tag = typeof(tag) !== 'undefined' ? tag : "div" 

也可以写成这样的大部分时间:

tag = tag || 'div' 

也许您的问题就在这里,有很多的this回事...

$.each(this.properties(), function() { 
    var hash = this.indexOf("Color") !== -1 ? '#' : ''; 
    var property = typeof(element[this]) === 'number' ? element[this] * Nx.ratio : element[this]; 
    css[this] = hash + property; 
}) 

什么this.properties()this是否与this相同each(...)?似乎有错误的来源...

+0

非常感谢,Frédéric是对的,我应该在我的数字末尾添加一个“px”。但感谢您的提示,我从来不知道tag = tag || 'div'...有没有我能找到更多这种简写代码的地方? – 2012-04-25 10:22:21