텍스트 영역에서 커서의 '행 번호'(행)를 찾아서 추적하고 싶습니다. ('더 큰 그림'은 물론 텍스트가 붙여 넣어지지 않은 경우 새로운 줄이 생성/수정/선택 될 때마다 줄의 텍스트를 구문 분석하는 것입니다. 이렇게하면 설정된 간격으로 전체 텍스트를 반드시 구문 분석하지 않아도됩니다.)텍스트 영역에서 커서의 '행'(행) 번호를 확인하십시오.
StackOverflow에는 몇 가지 게시물이 있지만 아무도 특별히 내 질문에 대답하지 않습니다. 대부분의 질문은 픽셀 단위의 커서 위치 또는 텍스트 영역 외의 줄 번호 표시입니다.
내 시도는 1 행부터 시작하여 텍스트 영역을 벗어날 때 잘 동작합니다. textarea를 클릭하고 다른 줄에 다시 올리면 실패합니다. 시작 줄이 1이 아니기 때문에 텍스트를 붙여 넣을 때도 실패합니다.
내 JavaScript 지식이 제한되어 있습니다.
<html>
<head>
<title>DEVBug</title>
<script type="text/javascript">
var total_lines = 1; // total lines
var current_line = 1; // current line
var old_line_count;
// main editor function
function code(e) {
// declare some needed vars
var keypress_code = e.keyCode; // key press
var editor = document.getElementById('editor'); // the editor textarea
var source_code = editor.value; // contents of the editor
// work out how many lines we have used in total
var lines = source_code.split("\n");
var total_lines = lines.length;
// do stuff on key presses
if (keypress_code == '13') { // Enter
current_line += 1;
} else if (keypress_code == '8') { // Backspace
if (old_line_count > total_lines) { current_line -= 1; }
} else if (keypress_code == '38') { // Up
if (total_lines > 1 && current_line > 1) { current_line -= 1; }
} else if (keypress_code == '40') { // Down
if (total_lines > 1 && current_line < total_lines) { current_line += 1; }
} else {
//document.getElementById('keycodes').innerHTML += keypress_code;
}
// for some reason chrome doesn't enter a newline char on enter
// you have to press enter and then an additional key for \n to appear
// making the total_lines counter lag.
if (total_lines < current_line) { total_lines += 1 };
// putput the data
document.getElementById('total_lines').innerHTML = "Total lines: " + total_lines;
document.getElementById('current_line').innerHTML = "Current line: " + current_line;
// save the old line count for comparison on next run
old_line_count = total_lines;
}
</script>
</head>
<body>
<textarea id="editor" rows="30" cols="100" value="" onkeydown="code(event)"></textarea>
<div id="total_lines"></div>
<div id="current_line"></div>
</body>
</html>
, 당신은 행 의미합니까? 텍스트를 말할 때 줄과 줄이 같지 않습니다. 고정 폭 글꼴이 아닌 경우 열이 없습니다. – Anurag
죄송합니다. 예, 행을 의미합니다. 원래 게시물을 업데이트 할 것입니다. – ethicalhack3r