javascript 内置的HTML编辑器显示“矩形”

rqmkfv5c  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(124)

我编写了一个HTML编辑器,但是它不工作了。不久前它还能工作,但是可能是我姐姐编辑了代码(她实际上对HTML一无所知)
现在的问题是,每当我按下回车键,而不是简单地移动到下一行,一个矩形创建,为什么?
下面是代码:

const first = document.querySelector(".first");
const iframe = document.querySelector("iframe");
const btn = document.querySelector("button");

btn.addEventListener("click", () => {
  var html = first.textContent;
  iframe.src = "data:text/html;charset=utf-8," + encodeURI(html);
});

first.addEventListener('keyup',()=>{
  var html = first.textContent;
  iframe.src = "data:text/html;charset=utf-8," + encodeURI(html);
})

first.addEventListener("paste", function(e) {
        e.preventDefault();
        var text = e.clipboardData.getData("text/plain");
        document.execCommand("insertText", false, text);
    });
* {
 box-shadow: 0 2px 3px black;
 position: fixed;
 height: 100vh;
 justify-content: center;
 align-items: center;
 border: 7px solid #36383f;
}

.first {
  background-color: #ffffff;
  width: 50%;
  overflow-x: hidden;
  overflow-y: auto;
  white-space: pre;
  box-shadow: 0 1px 1px rgb(22, 22, 22);
  outline: none;
  padding: 0.4rem;
  height: 90vh;
}

.second {
  background-color: rgb(255, 255, 255);
  width: 50%;
  overflow-y: auto;
  white-space: pre;
  right: 0;
  box-shadow: 0 1px 1px rgb(22, 22, 22);
  padding: 0.4rem;
  height: 90vh;
}
<div class="main-editor">
  <button class="btn">Run</button>
  <div  class="first" contenteditable>writecode</div>
  <iframe class="second" > </iframe>
</div>
vxf3dgd4

vxf3dgd41#

因为你在所有元素上都加了box-shadowborder,把*去掉,我把*改成.first, .second

const first = document.querySelector(".first");
const iframe = document.querySelector("iframe");
const btn = document.querySelector("button");

btn.addEventListener("click", () => {
  var html = first.textContent;
  iframe.src = "data:text/html;charset=utf-8," + encodeURI(html);
});

first.addEventListener('keyup',()=>{
  var html = first.textContent;
  iframe.src = "data:text/html;charset=utf-8," + encodeURI(html);
})

first.addEventListener("paste", function(e) {
        e.preventDefault();
        var text = e.clipboardData.getData("text/plain");
        document.execCommand("insertText", false, text);
    });
.first, .second {
 box-shadow: 0 2px 3px black;
 position: fixed;
 justify-content: center;
 align-items: center;
 border: 7px solid #36383f;
}

.first {
  background-color: #ffffff;
  width: 50%;
  overflow-x: hidden;
  overflow-y: auto;
  white-space: pre;
  box-shadow: 0 1px 1px rgb(22, 22, 22);
  outline: none;
  padding: 0.4rem;
  height: 90vh;
}

.second {
  background-color: rgb(255, 255, 255);
  width: 50%;
  overflow-y: auto;
  white-space: pre;
  right: 0;
  box-shadow: 0 1px 1px rgb(22, 22, 22);
  padding: 0.4rem;
  height: 90vh;
}
<div class="main-editor">
  <button class="btn">Run</button>
  <div  class="first" contenteditable>writecode</div>
  <iframe class="second" > </iframe>
</div>

相关问题