简体   繁体   English

JavaScript:当文本位于文本区域内时,所选文本不会被替换

[英]JavaScript: Selected text is not getting replaced when the text is inside a textarea

I have a problem replacing a selected text inside a textarea with a predefined replacement text. 我在用预定义的替换文本替换文本区域内的选定文本时遇到问题。

To replace a text, I have to select it and right click. 要替换文本,我必须选择它并右键单击。

The replacement happens properly, if the text is inside a <div> or a <p> tag. 如果文本在<div><p>标记内,则替换将正确进行。 But if the text is inside a <textarea> , it is not getting replaced correctly. 但是,如果文本在<textarea>内部,则无法正确替换。

A sample is available in this Fiddle 小提琴中有一个样本

Here is my code: 这是我的代码:

HTML: HTML:

<p> Select any text in this sentence and right click to replace it </p>

 <div>
  <textarea name = "intro" rows = "5" cols = "80">This text is not getting replaced as expected
  </textarea>
</div>

JS: JS:

if (document.addEventListener) {
    document.addEventListener('contextmenu', function(e) {
        replaceSelectedText("<<replaced>>");
        e.preventDefault();
    }, false);
} else {
    document.attachEvent('oncontextmenu', function() {
        alert("You've tried to open context menu");
        window.event.returnValue = false;
    });
}

function replaceSelectedText(replacementTxt) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        console.log(sel);
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            console.log(range);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementTxt));
        }
    } else if (document.selection && document.selection.createRange) {
        console.log("!!")
        range = document.selection.createRange();
        range.text = replacementTxt;
    }
}

Is there something wrong with the way I implemented it? 我的实施方式有问题吗?

Any suggestions would be appreciated. 任何建议,将不胜感激。

You should use .value to change the text of the textarea. 您应该使用.value更改文本区域的文本。

Look at this question 看这个问题

The range container that you get for the selected text in the textarea is the div itself and not the textarea element. 您为textarea的选定文本获得的范围容器是div本身,而不是textarea元素。 Therefore, when you try to insertNode a replacement text, it becomes a sibling of the textarea . 因此,当您尝试将替换文本插入节点时,它将成为textarea的同级对象。

More information from here . 这里获得更多信息。

The problem with textarea elements is that they do not hold their contents in DOM nodes. textarea元素的问题在于它们不将其内容保存在DOM节点中。 The text value is a property of the element. 文本值是元素的属性。 When you call range.selectNode, what happens is that the range is set so as to encompass the node you pass to the function and the children node of this node, but since a textarea does not store its text in children nodes, then you select only the textarea. 当您调用range.selectNode时,发生的情况是设置了范围,使其包含传递给函数的节点以及该节点的子节点,但是由于textarea不在其子节点中存储其文本,因此您选择只有文本区域。

You need to string replace by using the text area's selection properties and manipulate the string itself and not the DOM. 您需要使用文本区域的选择属性进行字符串替换,并操纵字符串本身而不是DOM。

The problem is that the text inside a textarea cannot be accessed using window.getSelection . 问题是无法使用window.getSelection访问textarea中的文本。

To access the text, there are different selection API namely selectionStart (The index of the beginning of selected text) and selectionEnd (The index of the end of selected text). 要访问文本,有不同的选择API,即selectionStart (所选文本开头的索引)和selectionEnd (所选文本结尾的索引)。

Here is the JS code: 这是JS 代码:

function ShowSelectionInsideTextarea(replacementText, eleID)
{
    var textComponent = document.getElementById(eleID);

    if (textComponent.selectionStart != undefined)
      {
        var mainStr = document.getElementById(eleID).value;
        var startPos = textComponent.selectionStart;
        var endPos = textComponent.selectionEnd;
        selectedText = textComponent.value.substring(startPos, endPos);
        mainStr= mainStr.replace(selectedText, replacementText);
        document.getElementById(eleID).innerHTML=mainStr;      
      }
}

Here is a live DEMO 这是现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM