在所选文字周围插入标签 [英] Insert tags around selected text

查看:159
本文介绍了在所选文字周围插入标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了一下,但其他答案并没有真正帮助我。



我想创建一个小型的所见即所得编辑器,只需要是添加链接和添加列表的选项。我的问题是,当点击链接/按钮之一(例如添加链接)时,如何在textarea的选定文本周围添加标签? / div>

我已经写了一个jQuery插件来实现这个功能(我真的必须记录它),您可以从 http://code.google.com/p/rangyinputs/downloads/list



以下将在所有主流浏览器中运行并围绕所选文本,并将选择恢复为包含之前选定的文本:

  var url =https://stackoverflow.com/; 
$(#yourTextAreaId)。surroundSelectedText('< a href ='+ url +'>','< / a>');

对于没有jQuery的解决方案,您可以使用 getInputSelection() code>和 setInputSelection()函数来自此答案以符合IE< = 8的兼容性,如下所示:

function getInputSelection(el){var start = 0,end = 0,normalizedValue,range,textInputRange,len,endRange; (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 \\\
/ g,\\\
); //创建一个仅在输入中生效的TextRange textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); //检查选择的开始和结束是否在输入的最后,因为在这种情况下moveStart / moveEnd不会返回我们想要的// endRange = el.createTextRange(); endRange.collapse(假); if(textInputRange.compareEndPoints(StartToEnd,endRange)> -1){start = end = len; } else {start = -textInputRange.moveStart(character,-len); start + = normalizedValue.slice(0,start).split(\\\
)。length - 1; if(textInputRange.compareEndPoints(EndToEnd,endRange)> -1){end = len; } else {end = -textInputRange.moveEnd(character,-len); end + = normalizedValue.slice(0,end).split(\\\
)。length - 1; }}}} return {start:start,end:end};} function offsetToRangeCharacterMove(el,offset){return offset - (el.value.slice(0,offset).split(\r\\\
) (typeof el.selectionStart ==number&& typeof el.selectionEnd ==number){el.selectionStart = startOffset; el.selectionEnd = endOffset; } else {var range = el.createTextRange(); var startCharMove = offsetToRangeCharacterMove(el,startOffset); range.collapse(真); if(startOffset == endOffset){range.move(character,startCharMove); } else {range.moveEnd(character,offsetToRangeCharacterMove(el,endOffset)); range.moveStart(character,startCharMove); } range.select(); }} function surroundSelectedText(el,before,after){var val = el.value; var sel = getInputSelection(el); el.value = val.slice(0,sel.start)+ before + val.slice(sel.start,sel.end)+ after + val.slice(sel.end); var newCaretPosition = sel.end + precedinglength + after.length; setInputSelection(el,newCaretPosition,newCaretPosition);} function surroundWithLink(){surroundSelectedText(document.getElementById(ta),'< a href =https://stackoverflow.com/>','< a>');}

< input type =按钮onmousedown =surroundWithLink(); return falsevalue =Surround>< br>< textarea id =tarows =5cols =50>在这里选择一些文字并按下按钮< / textarea>



如果您不需要支持对于IE <= 8,可以用以下代替 getInputSelection() setInputSelection()函数: / p>

 函数getInputSelection(el){
return {
start:el.selectionStart,
end :el.selectionEnd
};
}

函数setInputSelection(el,start,end){
el.setSelectionRange(start,end);
}


I've had a look around but the other answers don't really help me out.

I want to create a small WYSIWYG editor, there only needs to be the options to add links and add lists. My question is how do I append tags around selected text in a textarea when one of the links/button (e.g. "Add Link") is clicked?

解决方案

I've written a jQuery plug-in that does this (and which I really must document), which you can download from http://code.google.com/p/rangyinputs/downloads/list.

The following will work in all major browsers and surrounds the selected text, and restores the selection to contain the previously selected text:

var url = "https://stackoverflow.com/";
$("#yourTextAreaId").surroundSelectedText('<a href="' + url + '">', '</a>');

For a solution without jQuery, you could use the getInputSelection() and setInputSelection() functions from this answer for compatibility with IE <= 8 as follows:

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");

            // Create a working TextRange that lives only in the input
            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 offsetToRangeCharacterMove(el, offset) {
    return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
}

function setInputSelection(el, startOffset, endOffset) {
    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        el.selectionStart = startOffset;
        el.selectionEnd = endOffset;
    } else {
        var range = el.createTextRange();
        var startCharMove = offsetToRangeCharacterMove(el, startOffset);
        range.collapse(true);
        if (startOffset == endOffset) {
            range.move("character", startCharMove);
        } else {
            range.moveEnd("character", offsetToRangeCharacterMove(el, endOffset));
            range.moveStart("character", startCharMove);
        }
        range.select();
    }
}

function surroundSelectedText(el, before, after) {
  var val = el.value;
  var sel = getInputSelection(el);
  el.value = val.slice(0, sel.start) +
             before +
             val.slice(sel.start, sel.end) +
             after +
             val.slice(sel.end);
  var newCaretPosition = sel.end + before.length + after.length;
  setInputSelection(el, newCaretPosition, newCaretPosition);
}

function surroundWithLink() {
  surroundSelectedText(
    document.getElementById("ta"),
    '<a href="https://stackoverflow.com/">',
    '</a>'
  );
}

<input type="button" onmousedown="surroundWithLink(); return false" value="Surround">
<br>
<textarea id="ta" rows="5" cols="50">Select some text in here and press the button</textarea>

If you don't need support for IE <= 8, you can replace the getInputSelection() and setInputSelection() functions with the following:

function getInputSelection(el) {
  return {
    start: el.selectionStart,
    end: el.selectionEnd
  };
}

function setInputSelection(el, start, end) {
  el.setSelectionRange(start, end);
}

这篇关于在所选文字周围插入标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆