我正在尝试使用html的contenteditable div
创建在线代码编辑器。
用户将在div
中编辑其代码,该代码最多支持19
,而无需滚动div
。
我想做的是为每行设置一个行号。
但是您可以看到,当用户正在编辑使div
溢出并使div
滚动的代码时,行号不会改变。为了解决这个问题,我想知道有关div
滚动的y坐标。例如,如果只有3行,则div
不滚动,则代码返回0
,如果有100行,并且插入号当前位于第100行,则使div
滚动,代码返回100-19 = 81
。
这里是代码:
var textbox = document.getElementById("textbox");
var row_text = document.getElementById("row-text");
function update(){
//line numbers text. For example, if the top line's number should be 1, then it should return `1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19`
row_text.innerHTML="1\n2\n3";
}
setInterval(update, 1);
body{
background-color: #24292E;
}
#textbox-container{
border: 0.5px white solid;
width: 500px;
height: 300px;
left: 50%;
position: relative;
transform: translate(-248px, 2px);
}
#textbox{
width: 480px;
height: 292px;
resize: none;
left: 50%;
position: relative;
transform: translate(-233px, 2px);
overflow: hidden;
background-color: #24292E;
color: white;
font-family: 'Source Code Pro', monospace;
outline: none;
font-size: 12px;
overflow: hidden;
}
p{
width: 0px;
height: 0px;
margin: 0px;
transform: translate(3px, 2px);
font-family: 'Source Code Pro', monospace;
font-size: 12px;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!--<link rel="stylesheet" type="text/css" href="style.css"></link>-->
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@700&display=swap" rel="stylesheet">
</head>
<body>
<div id="textbox-container">
<p id="row-text"></p>
<div id="textbox" cols="50" rows="5" contenteditable="true"></div>
</div>
<!--<script src="script.js"></script>-->
</body>
</html>
是否有可能获得有关滚动的y坐标?
const textbox = document.getElementById('textbox');
const logger = document.getElementById('logger');
const bottomLogger = document.getElementById('bottomLogger');
setInterval(() => {
logger.value = textbox.scrollTop + 'px'; // Indentation from above
loggerRow.value = textbox.scrollTop / 15; // row number
bottomLogger.value = textbox.scrollHeight / 15;
}, 40)
#textbox {
background: aqua;
height: 150px;
width: 300px;
max-height: 150px;
overflow-y: scroll;
font-size: 13px;
line-height: 15px;
}
<div id=textbox contenteditable rows=5></div>
<ul>
<li>
<input id=logger>
</li>
<li>
<label>
<strong>Row number</strong>
<input id=loggerRow>
</label>
</li>
<li>
<label>
<strong>Bottom row</strong>
<input id=bottomLogger>
</label>
</li>
</ul>