Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

javascript - 如何从一开始就以字符形式在textarea中获取插入符号列(不是像素)的位置?(How to get the caret column (not pixels) position in a textarea, in characters, from the start?)

How do you get the caret position in a <textarea> using JavaScript?(你如何使用JavaScript获得<textarea>的插入位置?)

For example: This is| a text(例如: This is| a text) This is| a text This should return 7 .(这应该返回7 。) How would you get it to return the strings surrounding the cursor / selection?(如何让它返回光标/选择周围的字符串?) Eg: 'This is', '', ' a text' .(例如: 'This is', '', ' a text' 。) If the word “is” is highlighted, then it would return 'This ', 'is', ' a text' .(如果单词“is”突出显示,则返回'This ', 'is', ' a text' 。)   ask by Restless Wanderer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:(使用Firefox,Safari(以及其他基于Gecko的浏览器),您可以轻松使用textarea.selectionStart,但对于不起作用的IE,您必须执行以下操作:)

function getCaret(node) { if (node.selectionStart) { return node.selectionStart; } else if (!document.selection) { return 0; } var c = "01", 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; } ( complete code here )(( 这里完整代码 )) I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...(我还建议你检查jQuery FieldSelection插件,它允许你这样做以及更多......) Edit: I actually re-implemented the above code:(编辑:我实际上重新实现了上面的代码:) 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; } Check an example here .(点击这里查看示例。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...