编辑文本区域中的选定文本并将其打印回textarea

时间:2014-05-30 13:01:03

标签: javascript select replace nicedit

过去几天我一直在使用javascript来处理一个问题,我现在意识到我应该从一开始就重新考虑它,因为我不能让它工作。

PS。它需要在IE8 +,Chrome,FF:s中工作 PSS。使用nicEdit,我的js是一个插件

基本上我想做的是:

  • 从文本区域中选择文字
  • 点击一个启动我的javascript(获得此排序)
  • 的按钮
  • 选择所选文字并放置<预> < /预>标签,或其他什么,围绕它
  • 将其粘贴回textarea。

我无法解决的问题是:

  • 选择并替换多行文字
  • 让标签成为实际标签而不仅仅是印刷文本
  • 请确保我选择的实际文本是替换内容,而不是文本的首次出现。
  • 让文本保留新行,缩进,奇数等内容。

一个例子:

  

Lorem ipsum dolor sit amet,consectetur adipisicing elit,   sed do eiusmod tempor

     

incididunt ut labore et dolore magna

     

aliqua。)< - 我标记了这个文字 Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。

并将其转换为:

  

Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do   eiusmod tempor

     

(incididunt ut labore et dolore magna

     

aliqua。)< - 使用我的标签全部加粗 Ut enim ad minim veniam,quis   nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo   consequat。

我可以链接我的JS函数,如果这有任何帮助,perheps它可以建立它,但我被困在了。

function() {        
    var textComponent = document.getElementById('area1');
    var selectedText;

    if (document.selection != undefined){
      selectedText = (!!document.getSelection) ? document.getSelection() :
         (!!window.getSelection)   ? window.getSelection() :
         document.selection.createRange().text;
    }

    //Mozilla/Chrome version same as prev atm
    else if (textComponent.selectionStart != undefined){
      selectedText = (!!document.getSelection) ? document.getSelection() :
         (!!window.getSelection)   ? window.getSelection() :
         document.selection.createRange().text;
    }

    var nicE = nicEditors.findEditor('area1');
    var cont = nicE.getContent();
    var str = nicE.getContent();
    var res = str.replace(selectedText,'<pre class="codePrint"><code>' + selectedText + '</code></pre>');

    nicE.setContent(res);
}

我不知道这段代码是否有用,但谁知道呢。它的作用是什么,找到我标记的文本并替换它(但只有1行和第一次出现,如果我在bb标记aa bbbb bb cc,那么而不是获取aa bbbb bb cc,我得到aa bb bb bb cc,这不是我想要的我想我需要替换给定结束的特定内容并开始选定区域的位置,但我不知道如何附加这些内容。

1 个答案:

答案 0 :(得分:0)

我通过制作div <div contenteditable="true"></div>解决了这个问题,然后使用了以下代码:

myEditor.prototype.surroundElement = function(tag,cssClass){

if(window.getSelection(document.getSelection().anchorNode) < 1){        
    if(document.getSelection().anchorNode.parentNode.nodeName == tag.toUpperCase()){

        var anchor = $(document.getSelection().anchorNode);

        anchor.unwrap();            
    }
}

else{

    var range = window.getSelection().getRangeAt(0);
    var newParent = document.createElement(tag);

    newParent.className = cssClass;

    try{

        range.surroundContents(newParent);
    } catch(err){

        alert("You may only style code within the same tag");
    }
}
};

使用range.surroundContents(newParent);我有一个已定义的函数为我处理标记。我需要做的是确保选择不包括几个不同的标签。它仅适用于一个标签。我通过清除通过换行符等创建的div标签并尝试错误检查来处理它。我对用户负有一些不理想的责任,但是因为我们有3个人会使用我创建的东西,这是可以接受的。

PS。第一个if语句允许我使用相同的按钮添加标签(完整选择)并删除它们(当前插入位置周围的标签)

相关问题