如何知道可内容编辑div的滚动Y坐标?



我正在尝试使用html的内容可编辑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 `1n2n3n4n5n6n7n8n9n10n11n12n13n14n15n16n17n18n19`
row_text.innerHTML="1n2n3";
}
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>

滚动顶部接口 滚动高度接口

最新更新