我有两个变量:
customBlock
女巫是<div class="column" used="true"></div>
customStyle
女巫是style="background: yellow"
如何将黄色背景指定给customBlock
?
一种选择是获得黄色&#39;字符串中的单词并使用
customBlock.setAttribute('background', yelloVariable)
但我正在寻找(在javascript中不是jquery)这样的东西:customBlock.magic(customStyle)
答案 0 :(得分:1)
编辑:
<强> 1。如果你想要魔术,这至少是一行:
customBlock.outerHTML = customBlock.outerHTML.split("<div").join("<div " + customStyle);
<强> 2。否则强>
迭代样式语句(我注意到我迟到了我将customStyle
视为样式声明,而不是HTML:这可以很容易地修复)
// Break down by semi-colon separated statements
styleList = customStyle.split(";");
//Iterate through
for ( var i=0; i<styleList.length; i++ ) {
//Break down statement into before and after colon
var statement = styleList[i].split[":"];
if ( ! statement[1] ) {
//No colon: could just be empty statement or the empty string after the last semicolon
continue;
}
//Trim whitespace from key
var key = statement[0].split(" ").join("");
//Set style
customBlock.style[key] = statement[1];
}
编辑:我只是注意到您的customStyle
是HTML;我在这里对待它就像一个有效的CSS字符串。
答案 1 :(得分:0)
var customBlock = "<div id='cB' class='column' used='true'></div>"; //A STRING. NOTE: I GAVE THE DIV AN ID
var customStyle = "background-color: yellow; width:50px; height:50px"; //I GAVE IT DIMENSIONS SO YOU CAN SEE IT
var attachColumn = document.body.innerHTML+=customBlock;//ADD CUSTOMBLOCK TO SOMETHING IN THE DOCUMENT - eg. THE BODY
document.getElementById("cB").style=customStyle; //REFERENCING THE ID OF THE ELEMENT THAT IS NOW IN THE DOM, WE ADD THE STYLE ATTRIBUTE
&#13;
<body></body>
&#13;