I have an HTML page with TextArea and label, I need to write CSS classes in the TextArea and use that by the label:
<textarea id="txtCSS" name="txtCSS" rows="4" cols="50">
.FC{color:green;}
</textarea>
<label class="FC">Some Text</label>
How to do that.
Try this
const css = function() { const [_,clas,css] = document.getElementById("txtCSS").value.match(/\\.(\\w+){(.*)}/) document.querySelector("."+clas).style=css; } document.getElementById("txtCSS").addEventListener("input",css) css()
<textarea id="txtCSS" name="txtCSS" rows="4" cols="50"> .FC{color:green;} </textarea> <label class="FC">Some Text</label>
Append the value of textarea into the style
tag.
input
on textarea to collect the new contentstyle
tag by id previewStyle
if exist then we just only append text otherwise, we have to create a new style
tag and append content into this one.Here is the DEMO
function render(value) {
let previewStyle = document.getElementById('previewStyle');
if(!previewStyle) {
addStyle(value);
}else {
previewStyle.innerText = value;
}
}
function addStyle(styles) {
/* Create style document */
const css = document.createElement('style');
css.type = 'text/css';
css.id = 'previewStyle';
if (css.styleSheet){
css.styleSheet.cssText = styles;
} else {
css.appendChild(document.createTextNode(styles));
}
/* Append style to the tag name */
document.getElementsByTagName("head")[0].appendChild(css);
}
const text = document.getElementById('txtCSS');
text.addEventListener('input', (e) => {
const content = e.target.value;
render(content);
});
render(text.value);
Please consider using library replace with current textarea for some advanced code highlight such as:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.