请注意换行和换行符的区别。 示例:
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
<textarea rows="2" cols="20" name="usrtxt" wrap="soft">
I'am only one line without line breaks. Look joe I don't break but I wrap.
</textarea>
<input type="submit">
</form>
</body>
</html>
https://jsfiddle.net/b5dtjvbo/1/
我想知道光标是在第一行还是最后一行。就像在textarea的顶部或底部。
答案 0 :(得分:1)
你可以这样做,你可以得到鼠标的位置
var indicator = document.getElementById("indicator");
var textarea = document.getElementById("textarea");
setInterval(function() {
indicator.value = caret(textarea);
}, 100);
function caret(node) {
if(node.selectionStart) return node.selectionStart;
else if(!document.selection) return 0;
var c = "\001";
var sel = document.selection.createRange();
var dul = sel.duplicate();
var len = 0;
dul.moveToElementText(node);
sel.text = c;
len = (dul.text.indexOf(c));
sel.moveStart('character',-1);
sel.text = "";
return len;
}
<textarea id="textarea" style="width:80%;height:100px;">
I'am only one line without line breaks. Look joe I don't break but I wrap.
</textarea><br>
<input type="text" id="indicator" style="width:25px;">
答案 1 :(得分:1)
唯一的解决方案是对textarea进行像素测量,并计算那些像素宽度适合多少字母?
答案 2 :(得分:0)
请参阅以下摘录
<html>
<head>
<script>
function f1(el) {
var val = el.value;
var position=val.slice(0,el.selectionStart).length;
// alert(position)
if(parseInt(position)>=0 && parseInt(position)<=18)
alert("cursor is on top line")
else if(parseInt(position)>=19 && parseInt(position)<=39)
alert("cursor is on middle line")
else
alert("cursor is on last line")
}
</script>
</head>
<body>
<textarea rows="2" cols="20" id='t1' name="usrtxt" wrap="soft" onclick="f1(document.getElementById('t1'))">
I'am only one line without line breaks. Look joe I don't break but I wrap.
</textarea>
</body>
</html>
我编辑的答案........
我尝试在添加更多行后动态获取位置
为此我提到https://github.com/component/textarea-caret-position 这个网址,并修改原始源代码
请参考以下jsfiddle https://jsfiddle.net/6u1gwfeh/1/
希望这符合您的要求!!