如何从一开始就获得文本区域中插入符号列(而不是像素)的位置(以字符为单位)?控件中的插入符号位置是如何得到的。<textarea>使用JavaScript?例如:This is| a text这应该会回来7.如何让它返回围绕游标/选择的字符串?例如:'This is', '', ' a text'.如果突出显示“is”一词,那么它将返回。'This ', 'is', ' a text'.
3 回答
忽然笑
TA贡献1806条经验 获得超5个赞
function getCaret(node) { if (node.selectionStart) { return node.selectionStart; } else if (!document.selection) { return 0; } var c = "\001", sel = document.selection.createRange(), dul = sel.duplicate(), len = 0; dul.moveToElementText(node); sel.text = c; len = dul.text.indexOf(c); sel.moveStart('character',-1); sel.text = ""; return len;}
(
编辑:
function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }
潇潇雨雨
TA贡献1833条经验 获得超4个赞
function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); var add_newlines = 0; for (var i=0; i<rc.text.length; i++) { if (rc.text.substr(i, 2) == '\r\n') { add_newlines += 2; i++; } } //return rc.text.length + add_newlines; //We need to substract the no. of lines return rc.text.length - add_newlines; } return 0; }
添加回答
举报
0/150
提交
取消