jquery – selectionStart和selectionEnd在contenteditable元素中

前端之家收集整理的这篇文章主要介绍了jquery – selectionStart和selectionEnd在contenteditable元素中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在努力使用textarea的selectionStart和selectionEnd属性,使它们与contenteditable div元素一起工作.我在谷歌和SO上检查了很多相关文章,但没有效果.我有一些类似于以下的工作,完美的textarea.但是我希望这个可以与contenteditable div一起工作.
  1. function replaceVal(node,val,step){
  2. //...
  3. var cursorLoc = node.selectionStart;
  4. node.value = node.value.substring(0,node.selectionStart - step) + value +
  5. node.value.substring(node.selectionEnd,node.value.length);
  6. node.scrollTop = scrollTop;
  7. node.selectionStart = cursorLoc + value.length - step;
  8. node.selectionEnd = cursorLoc + value.length - step;
  9. //...
  10. }

这可以如何修改,以便它可以与contenteditable div元素而不是textarea一起使用?

解决方法

尝试这样,它返回所选的文本,无论是否内容可编辑.
  1. function GetSelectedText() {
  2.  
  3. if (document.getSelection) { // all browsers,except IE before version 9
  4. var sel = document.getSelection();
  5. // sel is a string in Firefox and Opera,// and a selectionRange object in Google Chrome,Safari and IE from version 9
  6. // the alert method displays the result of the toString method of the passed object
  7. alert(sel);
  8. }
  9. else {
  10. if (document.selection) { // Internet Explorer before version 9
  11. var textRange = document.selection.createRange();
  12. alert(textRange.text);
  13. }
  14. }
  15. }
  1. <div>Test Example Microsoft T-shirt Box</div>
  2. <button onClick="GetSelectedText()">Get text</button>

我在jsfiddler中做出这个例子
enter link description here

猜你在找的jQuery相关文章