2016-05-24 40 views
0

我有两个变量:如何使用变量设置属性样式?

customBlock女巫<div class="column" used="true"></div>

customStyle女巫style="background: yellow"

我如何分配黄色背景的customBlock? 一种选择是从字符串得到“黄”字,并使用
customBlock.setAttribute('background', yelloVariable)

但我期待(在JavaScript不是jQuery的)的东西干净这样的:customBlock.magic(customStyle)

+1

所以,你有无效的HTML的字符串,通常被认为是小于最佳实践HTML的另一个字符串,你想加入他们在一起吗?老实说,我会退后一步,试图用不同的方式处理这个问题,首先不涉及字符串中的HTML块。最好使用DOM。 – Quentin

回答

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字符串处理。

+0

已经尝试......我也试过customBlock.attributes.style – Cristian

+0

这是一种做法,但我想知道是否有'魔术'的方式。 – Cristian

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
<body></body>

相关问题