2016-10-25 28 views
-2

我有下面的函數創建一個叫當文檔的末尾一個新的文本節點,使用文本字段中的文本值:添加元素W用戶選擇後/文本節點

function addAfter() { 
     var elem = document.getElementById('textfield').value; 
     var h = document.createElement('span'); 
     var t = document.createTextNode(elem);  
     h.appendChild(t); 
     document.body.appendChild(h); 
    } 

什麼我希望它能夠在用戶選擇的文本之後立即添加文本(例如,當您單擊並拖動以選擇文本時)。什麼需要取代document.body.appendChild(h);這個工作?

+0

*「用戶選擇的文本」*是什麼意思? – adeneo

+0

如您所看到的那樣,當您單擊並拖動文本並將其突出顯示時 –

+0

沒有這個事件 – adeneo

回答

0

Try This JS Fiddle

這應該去做任何事情,但IE邊緣(我相信)

function getSelectionText() { 
    var text = ""; 
    if (window.getSelection) { 
     text = window.getSelection().toString(); 
    } else if (document.selection && document.selection.type != "Control") { 
     text = document.selection.createRange().text; 
    } 
    return text; 
} 

document.body.addEventListener('mouseup', function() { 
(window.getSelection()) ? addText(window.getSelection().toString(), window.getSelection().baseNode.parentNode) : addText(document.selection.toString(), document.selection.baseNode.parentNode); 
}); 

function addText(text, parent) { 
parent.appendChild(document.createTextNode(text)); 
} 

,這個作品是它使用mouseUp事件,以確定是否文本可能已選擇的方式。所選文本存儲在window.getSelected()或document.selected()之下 - 然後將該值以及所選文本的父項傳遞給addText函數。它使用文檔appendChild和createTextNode方法將捕獲的文本追加到DOM。

在以前的IE版本中,他們使用document.select(),但是在Edge中,他們切換到getSelection(與其他人一樣),但是他們沒有實現與獲取文本時返回的值相同的值,真的抓住父節點並輕鬆追加到該節點。

因此,簡而言之,這會給你你在找什麼,但它不是跨瀏覽器和似乎沒有成爲一個辦法做到這一點很容易。

0

我操縱了我在另一個feed上找到的解決方案。

function addAfter (isBefore) { 
var sel, range, node; 
var changeText = document.getElementById('textfield').value; 
var textAndCode = "<span class=\"correction\"> " + changeText + " </span>"; 
if (window.getSelection) { 
    sel = window.getSelection(); 
    if (sel.getRangeAt && sel.rangeCount) { 
     range = window.getSelection().getRangeAt(0); 
     range.collapse(isBefore); 

     // Range.createContextualFragment() would be useful here but was 
     // until recently non-standard and not supported in all browsers 
     // (IE9, for one) 
     var el = document.createElement("div"); 
     el.innerHTML = textAndCode; 
     var frag = document.createDocumentFragment(), node, lastNode; 
     while ((node = el.firstChild)) { 
      lastNode = frag.appendChild(node); 
     } 
     range.insertNode(frag); 
    } 
} else if (document.selection && document.selection.createRange) { 
    range = document.selection.createRange(); 
    range.collapse(isBefore); 
    range.pasteHTML(textAndCode); 
} 
} 

你只需要在價值傳遞的isBefore如果你想讓它出現後爲假。

相關問題