如何在textarea中添加html?

时间:2019-05-13 06:45:56

标签: html textarea

通过单击按钮更改div1和div2的位置后,我想在文本区域中输入html代码。我对html div父级所做的任何更改也应在textarea中进行更改。我不知道该怎么做? 目的是在数据库中发送已更改的div父级。

<style>
#parent{
width: 50px;
height: 100px;
padding: 10px;
background-color: grey;
}
#div1{
width: 50px;
height: 50px;
background-color: red;
}
#div2{
width: 50px;
height: 50px;
background-color: blue;
}
</style>

<div id="parent">
    <div id="div1"></div>
    <div id="div2"></div>
</div>

<button type="button"  onclick="myFunctionSwitch()" >Chenge texareaHTML</button>

<form>
<textarea rows="4" cols="30" id="showhtml">
<div id="parent">
    <div id="div1"></div>
    <div id="div2"></div>
</div>
</textarea>
</form>


<script>

function myFunctionSwitch() {

  document.getElementById("div1").remove();
  document.getElementById("div2").remove();

  var x = document.createElement('div');
  x.id = 'div2';
  document.getElementById("parent").appendChild(x);
  var y = document.createElement('div');
  y.id = 'div1';
  document.getElementById("parent").appendChild(y);


  document.getElementById("showhtml").innerHTML = x + y;
}

</script>

2 个答案:

答案 0 :(得分:1)

更改

<div id="parent">
    <div id="div1"></div>
    <div id="div2"></div>
</div>

<div id=container>
    <div id="parent">
        <div id="div1"></div>
        <div id="div2"></div>
    </div>

document.getElementById("showhtml").innerHTML = x + y;

document.getElementById("showhtml").innerHTML = 
document.getElementById("container").innerHTML;

这是工作代码:

function myFunctionSwitch() {

  document.getElementById("div1").remove();
  document.getElementById("div2").remove();

  var x = document.createElement('div');
  x.id = 'div2';
  document.getElementById("parent").appendChild(x);
  var y = document.createElement('div');
  y.id = 'div1';
  document.getElementById("parent").appendChild(y);


  document.getElementById("showhtml").innerHTML = document.getElementById("container").innerHTML;
}
#parent{
width: 50px;
height: 100px;
padding: 10px;
background-color: grey;
}
#div1{
width: 50px;
height: 50px;
background-color: red;
}
#div2{
width: 50px;
height: 50px;
background-color: blue;
}
<div id=container>
<div id="parent">
    <div id="div1"></div>
    <div id="div2"></div>
</div>
</div>

<button type="button"  onclick="myFunctionSwitch()" >Chenge texareaHTML</button>

<form>
<textarea rows="4" cols="30" id="showhtml">
<div id="parent">
    <div id="div1"></div>
    <div id="div2"></div>
</div>
</textarea>
</form>

答案 1 :(得分:0)

如果您在textarea中输入html,它将被转义并且不会被解析为html元素。

做你想要做的唯一方法是使用contenteditable属性。

查看此documentation