所以我做了一个代码块,你可以编辑和创建一个新的代码块,但问题是,它没有创建code
标签。这是我的代码:
<style>
html, body {
margin-top: 5px;
}
.codeblockDiv {
width: 50%;
}
.codeblock {
background: linear-gradient(to top, rgb(207, 207, 207) 16%, rgb(252, 252, 252) 79%);
border: 1px solid;
border-radius: 5px;
padding: 4px;
width: 50%;
display: inline-block;
outline: none;
}
.edit {
top: 0;
right: 300px;
position: absolute;
}
.cancel {
top: 0;
right: 350px;
position: absolute;
}
.new {
left: 9px;
top: 0;
position: absolute;
}
</style>
<body>
<button class="new" onclick="newCodeblock()">
New
</button>
<button class="edit" onclick="editCode()">
Edit
</button><br>
<code class="codeblock" id="codeBlock">
<!DOCTYPE html><br>
 <html><br>
  <head><br>
   <meta charset=“UTF-8”><br>
   <title>Example</title><br>
  </head><br>
<body><br>
 <div><br>
  <p>This is in a <code> tag</p><br>
 </div><br>
</body><br>
 </html>
</code><br>
<script>
function editCode() {
var x = document.getElementById('codeBlock');
x.setAttribute("contenteditable", "true")
var y = document.createElement('button')
y.innerHTML = "Cancel";
y.className = "cancel";
document.body.appendChild(y);
y.addEventListener('click', function() {
x.setAttribute("contenteditable", "false")
y.remove()
})
}
function boldText(e) {
if (e.keyCode == 17 && e.keyCode == 66) {
let textBox = document.querySelector('.codeblock');
textBox.style.fontWeight = 'bold';
}
}
function newCodeblock() {
var z = document.createElement('code');
var h = document.createElement('button');
z.className = "codeblock";
z.innerHTML = "Write Here"
z.setAttribute("contenteditable", "true");
h.innerHTML = "Save";
h.addEventListener('click', function() {
z.setAttribute("contenteditable", "false");
h.remove();
})
document.querySelector('.codeblockDiv').appendChild(h);
document.querySelector('.codeblockDiv').appendChild(x);
}
</script>
<div class="codeblockDiv">
</div>
</body>
这里JSFiddle
您的newCodeblock
函数引用了一个不存在的变量x
如果你改变
document.querySelector('.codeblockDiv').appendChild(x);
读
document.querySelector('.codeblockDiv').appendChild(z);
您的newCodeblock
函数将成功运行