给定一个 DIV w contenteditable,如何找到光标位置以提取子字符串
给出:
<div id="comment_content_new" contenteditable="true" tabindex="0">
<p>
<span class="tag" id="tag30">theTag</span> @rac
</p>
</div>
当光标位于@rac中的c之后时,我可以通过以下方式获取光标位置:
savedRange = window.getSelection().getRangeAt(0);
其中提供:
Range
collapsed: true
commonAncestorContainer: Text
endContainer: Text
endOffset: 5
startContainer: Text
startOffset: 5
我想要做的是给定光标位置,让所有内容向后移动,直到相对于光标位置的第一个@。鉴于该范围给了我错误的光标,我无法按照我一直在尝试的方式使用 .text() ,例如:
text = $('#comment_content_new p').text();
trigger = '@';
lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
关于如何实现这一点的任何想法?我意识到这不是一件容易的事!谢谢
Given:
<div id="comment_content_new" contenteditable="true" tabindex="0">
<p>
<span class="tag" id="tag30">theTag</span> @rac
</p>
</div>
When the cursor is after the c in @rac, I can get the cursor position with:
savedRange = window.getSelection().getRangeAt(0);
Which provides:
Range
collapsed: true
commonAncestorContainer: Text
endContainer: Text
endOffset: 5
startContainer: Text
startOffset: 5
What I want to be able to do is given the cursor position, get everything moving backwards until the first @, in relation to the cursor position. Given that range is giving me he wrong cursor, I can't use .text() the way I have been trying, something like:
text = $('#comment_content_new p').text();
trigger = '@';
lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
Any ideas on how I can pull this off? I realize it's not an easy one! thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样?
String.split: http://www.w3schools.com/jsref/jsref_split.asp
Array.pop: http://www.w3schools.com/jsref/jsref_pop.asp
How's that?
String.split: http://www.w3schools.com/jsref/jsref_split.asp
Array.pop: http://www.w3schools.com/jsref/jsref_pop.asp
如果您想要可靠且经过测试的跨浏览器解决方案,请尝试 http://code.google.com/p /rangy/
在这些方法中,有一种方法可以获取和设置插入符位置。
If you want a solid and tested cross-browser solution, try http://code.google.com/p/rangy/
Among the methods there is one to get and set caret position.