我一直在努力使用textarea的selectionStart和selectionEnd属性,使它们与contenteditable div元素一起工作.我在谷歌和SO上检查了很多相关文章,但没有效果.我有一些类似于以下的工作,完美的textarea.但是我希望这个可以与contenteditable div一起工作.
- function replaceVal(node,val,step){
- //...
- var cursorLoc = node.selectionStart;
- node.value = node.value.substring(0,node.selectionStart - step) + value +
- node.value.substring(node.selectionEnd,node.value.length);
- node.scrollTop = scrollTop;
- node.selectionStart = cursorLoc + value.length - step;
- node.selectionEnd = cursorLoc + value.length - step;
- //...
- }
这可以如何修改,以便它可以与contenteditable div元素而不是textarea一起使用?
解决方法
尝试这样,它返回所选的文本,无论是否内容可编辑.
- function GetSelectedText() {
- if (document.getSelection) { // all browsers,except IE before version 9
- var sel = document.getSelection();
- // sel is a string in Firefox and Opera,// and a selectionRange object in Google Chrome,Safari and IE from version 9
- // the alert method displays the result of the toString method of the passed object
- alert(sel);
- }
- else {
- if (document.selection) { // Internet Explorer before version 9
- var textRange = document.selection.createRange();
- alert(textRange.text);
- }
- }
- }
- <div>Test Example Microsoft T-shirt Box</div>
- <button onClick="GetSelectedText()">Get text</button>
我在jsfiddler中做出这个例子
enter link description here