我想找出並跟蹤textarea中光標的'行號'(行)。 (「更大的圖片」是每當創建/修改/選擇新行時解析行上的文本,當然不粘貼文本。這樣可以節省不必要的設置間隔解析整個文本。)找出textarea中光標的'行號'(行號)
在StackOverflow中有幾個帖子,但是他們沒有一個專門回答我的問題,大多數問題都是針對像素中的光標位置或顯示除textarea之外的行號。
我的嘗試如下,它在第1行開始並且不離開textarea時工作正常。點擊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 2012-02-07 23:35:45
對不起,是的,我的意思是排。我會更新我原來的帖子。 – ethicalhack3r 2012-02-07 23:38:21