javascript - 我试图在 textarea 顶部重叠 pre 标签,但它只是漂浮在其容器的中间
问题描述
我花了一些时间尝试在 textarea 顶部重叠 pre 标签,我正在尝试构建某种文本编辑器。但是,不知何故,pre 标记并未呈现在其容器的左上角,而是呈现在中间。没有边距或填充将其拉低,所以我没有想法。还有一件奇怪的事情发生了,textarea 有 position: absolute,但它的容器仍在将自己拉伸到 textarea 的高度。
出于沮丧,我从这个库中复制了确切的代码:http: //satya164.xyz/react-simple-code-editor/。但它仍然不起作用,即使它是完全相同的代码。
我当前的代码:
const codeEditor = document.getElementById("code-editor__textarea");
const codeRenderer = document.getElementById("code-editor__pre");
codeEditor.addEventListener("keyup", e => {
codeRenderer.innerHTML = codeEditor.value;
});
*,
:after,
:before {
box-sizing: inherit;
}
body {
font-family: monospace;
line-height: 1.5;
margin: 0;
}
.code-editor {
margin: 1.67em 0;
max-height: 400px;
overflow: auto;
}
.code-editor__container {
background-color: #fafafa;
box-sizing: border-box;
font-size: 12px;
font-variant-ligatures: common-ligatures;
position: relative;
text-align: left;
white-space: pre-wrap;
word-break: keep-all;
}
#code-editor__textarea,
#code-editor__pre {
-webkit-font-smoothing: antialiased;
display: inherit;
font-family: inherit;
font-size: inherit;
font-style: inherit;
font-variant-ligatures: inherit;
font-weight: inherit;
letter-spacing: inherit;
line-height: inherit;
padding: 10px;
tab-size: inherit;
text-indent: inherit;
text-rendering: inherit;
text-transform: inherit;
white-space: inherit;
word-break: inherit;
}
#code-editor__textarea {
-webkit-text-fill-color: transparent;
background: none;
border: none;
color: inherit;
height: 100%;
left: 0;
outline: 0;
overflow: hidden;
position: absolute;
resize: none;
top: 0;
width: 100%;
}
#code-editor__pre {
margin: 0;
pointer-events: none;
position: relative;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Code Editor</title>
</head>
<body>
<div class="code-editor">
<div class="code-editor__container">
<textarea id="code-editor__textarea" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea>
<pre id="code-editor__pre" aria-hidden="true"><br></pre>
</div>
</div>
</body>
</html>
解决方案
容器上的white-space: pre-wrap;
导致这种情况。
您已经使用绝对定位将 textarea 从流程中取出 - 但是它之前和之后的换行符仍然存在,并且因为您强制容器尊重它们,所以它们相应地将 pre 元素向下推。
(删除它也会使您的 textarea 依次具有较小的高度,因为它被设置为容器的 100% 高度。但我想这将是您想要的效果吗?)