简体   繁体   中英

Editable CSS by editing text on textarea?

How can I make a textarea which has the stylesheet of the web page inside it?

I want to make a web page which a user can customize its <style> settings by editing text inside a textarea .

Here's what I have done so far; inside the <textarea> of this code snippet is the editable text which I intend to make it function as the web page's stylesheet, but I'm not sure how to make it work.

I did many web search looking for solutions, but could not find useful help regarding this particular function. Any help will be appreciated.

 function myFunction() { document.getElementsByTagName("style")[0].innerHTML = "document.getElementById('input').value;"; }
 <p>sample text</p> <textarea id="input" oninput="myFunction()" rows="5">p { font-family: monospace; font-size: 15px; } </textarea>

You're very close, but your code has 2 problems.

  1. document.getElementsByTagName returns an array, so you need to select the first element of the array using [0] .
  2. You are not actually getting the input element, you're just using a string of the code you want to run (ie you want to run the code document.getElementById('input').value but you've put quotes around it, which turns it into a string).

This updated version should work:

 function myFunction() { document.getElementsByTagName("style")[0].innerHTML = document.getElementById('input').value; }
 <p>sample text</p> <textarea id="input" oninput="myFunction()" rows="5">html { font-family: monospace; font-size: 15px; } </textarea>

Another possibility is to use inline styles with the display style set to "block" and the contenteditable attribute set to "true".

Example:

<div>
  <style style="
      display: block; 
      padding: 0 0.5rem; 
      border: 1px solid black; 
      border-radius: 4px;
      white-space: pre;
      font-family: 'Courier New', Courier, monospace;
      font-size: small;
      " 
      contenteditable="true">
    #myDiv {
      height: 100%;
      --l1: repeating-linear-gradient(-60deg, 
        transparent 0, 
        transparent 5px, 
        rgba(210, 180, 140, 0.5) 0, 
        rgba(210, 180, 140, 0.5) 35px);
      --l0: repeating-linear-gradient(60deg,
        transparent 0, 
        transparent 5px,
        rgba(210, 180, 140, 0.5) 0, 
        rgba(210, 180, 140, 0.5) 35px);
      background: var(--l1), var(--l0);
      }
  </style>
  <div id="myDiv"></div>
</div>

This will directly allow to edit and alter the contents of the style definitions by the user, without the direct possibility to save the modifications.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM