如何通过JS或jQuery操作textarea中的选定文本?

时间:2014-12-17 08:32:16

标签: javascript jquery

我写了一个关于抓取所选文本的小片段,效果很好。 jsfiddle HTML

<textarea id="text">
    This is just a test!
</textarea>
<button>go</button>

JS

$(function(){
    $("button").on("click", function(){
        getWords();
    });
});

function getWords(){   
    var textComponent = document.getElementById('text');
    var selectedText;
    // IE version
    if (document.selection != undefined)
    {
        textComponent.focus();
        var sel = document.selection.createRange();
        selectedText = sel.text;
    }
    // Mozilla version
    else if (textComponent.selectionStart != undefined)
    {
        var startPos = textComponent.selectionStart;
        var endPos = textComponent.selectionEnd;
        selectedText = textComponent.value.substring(startPos, endPos)
    }
    //alert(selectedText);
    //whats next?
    //selectedText = "<p>"+selectedText+"</p>";
    //alert(selectedText);
}  

我可以抓取文字,但我如何设置或操作文字?例如,原始文本是

This is just a test!

我想用高亮显示的“测试!”包装一个p标签。

This is just
<p>a test!</p>

我能做到

selectedText = "<p>"+selectedText+"</p>"

但下一步是什么?如何将它放入textarea并保留其他文本?

THX!

4 个答案:

答案 0 :(得分:0)

表单字段(如textareas)仅显示纯文本(即,它不会在其中呈现HTML代码)。

答案 1 :(得分:0)

这应该有效:

var selectedText = textComponent.value.substring(startPos, endPos);
var precedingText = textComponent.value.substr(0, startPos - 1);
var followingText = textComponent.value.substr(endPos + 1);
textComponent.innerHTML = precedingText 
    + "<p>" + selectedText + "</p>" 
    + followingText;

但是对于浏览器无关的解决方案,你真的应该考虑使用jQuery。这很有趣。

答案 2 :(得分:0)

首先,p标签是否突出显示文字?如果是的话,那么......

有很多方法可以回答:

  1. DOM对象
  2.   

    var wrapper = document.createElement(&#34; p&#34;);

         

    wrapper.appendChild(textComponent);

         

    alert(wrapper.outerHTML);

    1. 使用Jquery
    2.   

      var wrapper = $(textComponent).wrap(&#34;&lt; p&gt;&#34;)[0];

           

      alert(wrapper.outerHTML);

      1. 简单的JS
      2.   

        textComponent.innerHTML =&#34;&lt; p为H.&#34; + textComponent.innerHTML +&#34;&lt; p为H.&#34 ;;

             

        alert(textComponent.outerHTML);

答案 3 :(得分:0)

尝试使用此代码:

$(function () {
    $("button").on("click", function () {
        var el = document.getElementById("text");
        replaceSelectedText(el);
    });
});

function getInputSelection(el) {
    var start = 0,
        end = 0,
        normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

function replaceSelectedText(el) {
    var sel = getInputSelection(el),
        val = el.value;
    text = '<p>'+val.slice(sel.start,sel.end)+'</p>';
    el.value = val.slice(0, sel.start) + text + val.slice(sel.end);
}