2016-05-24 66 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>

相關問題