[英]How can I work out whether the cursor in a textarea is in the first or last line, using JS or jQuery?
請注意換行和換行符的區別。 例:
<!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/
我想知道光標是在第一行還是最后一行。 就像在文本區域的頂部或底部。
你可以用這個做類似的事情你可以得到鼠標的位置
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;">
是對文本區域進行像素測量並計算那些像素寬度中可以容納多少個字母的唯一解決方案嗎?
請參考以下代碼段,
<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>
我編輯的答案........
我嘗試在添加更多行后動態獲得位置
為此,我引用此URL https://github.com/component/textarea-caret-position ,並修改原始源代碼
請參考以下jsfiddle https://jsfiddle.net/6u1gwfeh/1/
希望這符合您的要求!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.