【问题标题】:Setting the CSS of an html element with text entered by the user使用用户输入的文本设置 html 元素的 CSS
【发布时间】:2016-09-30 20:48:22
【问题描述】:

我的页面有两个文本区域和一个 div。一个textarea供用户输入html,另一个用于输入css。单击按钮时,我将调用 javascript 函数来显示 div 中的 css 和 html。

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 设置为文本?

编辑:我应该提到我希望能够放置类似的东西 .classExample{text-align:center} 在 css textarea 中并应用它。

【问题讨论】:

  • 无论如何div.style.cssText = css.value 会让你在输入中输入 CSS
  • 很遗憾没有成功
  • 你确定 div.style.cssText = "background-color: red"; 不起作用?
  • 设置一个能够添加多行的 3 列输入不是更有意义吗?因此,您将拥有 ID、类和 CSS,然后您可以根据需要添加或删除行,这样您就可以定位特定的 ID 或类名。
  • 我不太清楚你的意思。你能给我一个编码的例子吗?

标签: javascript html css


【解决方案1】:

是的,@adeneo 答案有效,这个 sn-p 显示了它。输入 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>

【讨论】:

  • 这只会设置整个 div 的样式。我应该澄清一下,我希望能够在 css 文本区域中使用类和 id。这有意义吗?
【解决方案2】:

假设您正在定义 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-27
    • 2021-09-22
    • 2020-03-03
    • 2020-01-26
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多