在我的一个 webApp 方法中,我动态创建 html 元素并使用此代码添加一个动态生成的 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);
这是从我的 console.log 中获取并传递给 css() 函数的 css 对象示例:
Object
backgroundColor: "#ff0000"
borderColor: "#ffffff"
borderStyle: "solid"
borderWidth: "0"
height: "56.865"
left: "0"
top: "274.29"
width: "893.115"
__proto__: Object
现在的问题是输出元素没有 top、left、height 和 width 属性,例如:
<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>
最佳答案
这些 CSS 属性不会应用于您的元素,因为您没有正确指定它们。 left
、top
、width
和 height
的值必须是:
- 一个数字,例如
0
或274.29
, - 或后跟单位后缀的字符串,例如
"0px"
或"274.29px"
。
您的代码使用没有单位后缀的字符串,因此这些值被认为是无效的并且这些属性将被忽略。
关于Jquery css 函数不使用映射中的所有参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10311200/