javascript 获取文本区域的行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12553025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting Line Number In Text Area
提问by Freelancer
Possible Duplicate:
Find out the 'line' (row) number of the cursor in a textarea
可能的重复:
找出文本区域中光标的“行”(行)号
I want to find out the line number that a user's cursor in on in a HTML textarea
element.
我想找出用户光标在 HTMLtextarea
元素中所在的行号。
Is this possible using javascript and jquery?
这可以使用 javascript 和 jquery 吗?
采纳答案by codingbiz
This works with button click. Stolen from Find out the 'line' (row) number of the cursor in a textarea
这适用于按钮单击。Stolen from在一个textarea中找出光标的'行'(行)号
?function getline()
{
var t = $("#t")[0];
alert(t.value.substr(0, t.selectionStart).split("\n").length);
}?
HTML
HTML
?<textarea rows="6" id="t">
there is no
love in the ghetto
so come here
and get it
</textarea>
<input type="button" onclick="getline()" value="get line" />??????????????????????????????????????????????????????????????????????
回答by Joyce Babu
You can use the following approach
您可以使用以下方法
- Find the caret position (index).
- Find the substring from position 0 to index
- Search for number of new lines in the substring obtained in step 2.
- 找到插入符号位置n(索引)。
- 查找从位置 0 到索引的子串
- 在步骤 2 中获得的子字符串中搜索新行数。
// Test
// 测试
$(function() {
$('#test').keyup(function() {
var pos = 0;
if (this.selectionStart) {
pos = this.selectionStart;
} else if (document.selection) {
this.focus();
var r = document.selection.createRange();
if (r == null) {
pos = 0;
} else {
var re = this.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
pos = rc.text.length;
}
}
$('#c').html(this.value.substr(0, pos).split("\n").length);
});
});
?
Here is a working example http://jsfiddle.net/S2yn3/1/
这是一个工作示例 http://jsfiddle.net/S2yn3/1/
回答by Bergi
This can be split up in three steps:
这可以分为三个步骤:
- Caret position in textarea, in characters from the start
- How to get the number of lines in a textarea?/ JavaScript: How to add line breaks to an HTML textarea?
- get the lines before the caret, and count them.
- textarea 中的插入符号位置,从开头开始的字符数
- 如何获取textarea中的行数?/ JavaScript:如何向 HTML 文本区域添加换行符?
- 获取插入符号之前的行,并计算它们。
I guess you don't want to consider wrapped text and scrolled content. Assuming you use the function from this answer, it would be like:
我猜您不想考虑包装文本和滚动内容。假设您使用此答案中的函数,它将类似于:
var el = document.getElementById("inputarea"); // or something
var pos = getCaret(el),
before = el.value.substr(0, pos),
lines = before.split(/\r?\n/);
return lines.length;