jQuery - get selection's paragraph, length, etc

柔情痞子 提交于 2019-12-08 13:35:17

问题


I'm trying to accomplish something I believe should be simple to do in jQuery.

I have a long text in my website. Whenever a user selects (highlights) a text, I need to get the following info:

  • The paragraph where the selection begins at
  • The char in that paragraph that the selection starts at
  • The length of the selection
  • The paragraph where the selection ends at (in case the highlight goes beyond one paragraph)
  • The char in that paragraph where the selection ends

Thanks ahead ;)


回答1:


I think I've answered all of these on Stack Overflow before. In turn:

  • A combination of getAncestor() from here and getSelectionBoundaryContainerElement() from here will do the job
  • It depends what you mean by "char in that paragraph that the selection starts at". If the paragraph may have other elements inside rather than just one text node, this becomes slightly tricky. You could adapt this.
  • Again, this depends on what you mean by the "length of the selection". You could get the selected text as a string and use its length property.
  • See answers for selection start
  • See answers for selection start

You'll need to do a little study of the APIs to do this, which is no bad thing.




回答2:


You need to use JavaScript for anything that deals with text selections. jQuery has no built in function for detecting where a selection begins or where it ends. Rangy http://code.google.com/p/rangy/ could be something you can use for such purpose.




回答3:


play around with

window.getSelection
document.getSelection
document.selection.createRange()

See an example on this site: http://www.codetoad.com/javascript_get_selected_text.asp



来源:https://stackoverflow.com/questions/7007357/jquery-get-selections-paragraph-length-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!