2016-09-30 83 views
0

我的頁面有兩個textareas和一個div。一個textarea用於輸入html,另一個用於輸入css。當一個按鈕被點擊時,我會調用一個javascript函數來顯示div內的css和html。使用用戶輸入的文本設置html元素的CSS

function handleLaunch() { 
 
    var div = document.getElementById('pane'); 
 
    var html = document.getElementById('h'); 
 

 
    var css = document.getElementById('c'); 
 

 
    div.innerHTML = html.value; 
 
    // This line obviously doesn't work div.style = css.value; 
 
}
<body> 
 
    <textarea id="c" placeholder="CSS code here..." rows="10" cols="50"></textarea> 
 
    <div id="pane"> 
 

 
    </div> 
 
    <br> 
 
    <textarea id="h" placeholder="Html code here..." rows="10" cols="50"></textarea> 
 
    <br> 
 
    <button type="button" onclick="handleLaunch()">Launch</button>

現在,如何設置CSS的文字?

編輯:我應該提到,我希望能夠在css textarea中放入類似 .classExample {text-align:center}的東西並使其適用。

+3

反正'div.style.cssText = css.value'會讓你鍵入CSS在輸入 – adeneo

+0

不幸的是,沒有工作 – Sidward

+0

你確定** div.style.cssText =「background-color:red」; **不起作用? – JonSG

回答

2

是的,@ adeneo答案的作品,這段代碼顯示它。輸入color: red;例如爲CSS,任何文本作爲HTML ...

function handleLaunch() { 
 
    var div = document.getElementById('pane'); 
 
    var html = document.getElementById('h'); 
 

 
    var css = document.getElementById('c'); 
 

 
    div.innerHTML = html.value; 
 
    div.style.cssText = css.value; 
 
}
<body> 
 
    <textarea id="c" placeholder="CSS code here..." rows="10" cols="50"></textarea> 
 
    <div id="pane"> 
 

 
    </div> 
 
    <br> 
 
    <textarea id="h" placeholder="Html code here..." rows="10" cols="50"></textarea> 
 
    <br> 
 
    <button type="button" onclick="handleLaunch()">Launch</button>

+0

這隻設置整個div的樣式。我應該澄清,我希望能夠在css textarea中使用類和id。這有意義嗎? – Sidward

1

假設你有選擇沿定義的CSS屬性,例如,你的CSS文字就像是

div{ 
    background:red; 
} 
.someClass{ 
    font-size:12px; 
} 

和你的HTML看起來像

<div>DIV content</div> 
<span class="someClass"> Content in someClass</span> 

您可以添加HTML作爲div.innerHTML = html.value;

但添加CSS到您的網頁,你將不得不做以下

var style = document.createElement('style'); 
style.type = 'text/css'; 
style.innerHTML = document.getElementById('c').value; 
document.getElementsByTagName('head')[0].appendChild(style) 
+0

謝謝!這是按我的意圖工作的 – Sidward

相關問題