web輕量級富文本框編輯


前言

  主要介紹squire,wangeditor富文本編輯
  以及用原生js 如何實現多個關鍵字標識

需求

  如何標記多個關鍵字,取消關鍵字

 

第一種方法 原生 textarea 標記

  准備資料參考:張鑫旭大大的博客 講得非常的清楚哦

  demo栗子:https://www.zhangxinxu.com/study/201104/range-miniblog-insert-topic.html

  推薦文章:JS Range HTML文檔/文字內容選中、庫及應用介紹

  知識點儲備:range對象, getSelection  MDN文檔直通車

  優點:原生實現的,不用額外引用第三方插件 

  缺點:功能稍微復雜一點 就難拓展了 全部自己寫 花費的時間比較長

 

  我的實踐項目經驗

  痛點一:不可以插入<span style='color:red'></span> 標記三四個關鍵字是沒有問題的,但是多個后 會標記的不准 計算的位置不准確。有嘗試用正則匹配,但是解決的不理想(這里還是個人寫的有問題)

  思路:通過range 可以得到當前選中文字的位置,得到的文本加入標識(比如插入話題是#),選中的文字獲取的位置包括插入的標識。之所以會導致位置計算不准<span>這個也是要記上的。

  但是這個長度也是固定的 不應該存在計算位置准確(由於寫法很久以前了 也沒有留存)希望在座的各位不會出現這種情況

  

  核心代碼

  

funGetSelected(element){
      // console.log(element.selectionStart, element.selectionEnd)
      //獲取選中內容
      if (!window.getSelection) { 
        //IE瀏覽器
        return document.selection.createRange().text;
      } else {
        return {
          selectedText: element.value.substr(element.selectionStart, element.selectionEnd - element.selectionStart),
          startPos: element.selectionStart,
          endPos: element.selectionEnd
        };  
      }
    },
funTextAsTopic(textObj, textFeildValue, flag){ textObj.focus();
if (textObj.createTextRange) { var caretPos = document.selection.createRange().duplicate(); document.selection.empty(); caretPos.text = textFeildValue; } else if (textObj.setSelectionRange) { var rangeStart = textObj.selectionStart; var rangeEnd = textObj.selectionEnd; var tempStr1 = textObj.value.substring(0, rangeStart); var tempStr2 = textObj.value.substring(rangeEnd); textObj.value = tempStr1 + textFeildValue + tempStr2; if(flag == 'delete'){ textObj.value = textObj.value.replace(`<${textFeildValue}>`, textFeildValue) } textObj.blur(); return textObj.value } },

 

 

 

  第二種方法 富文本框squire

 如果你不是用vue 也不是用react 或者ang  這個插件完全足夠了

 官網鏈接:http://neilj.github.io/Squire/

 優點:超級輕量  很靈活(比我接下來要介紹的 wangeditor 要 靈活)

 缺點:雖然我找到了npm 安裝包 但是import失敗 官網文檔上沒有看到寫

    也沒有看到哪個筒子寫了 如何引用成功(原生js 頁面是完全可以的)

    其他的 倒是沒有體驗太多

 

  貼主要代碼 這個我有一個完全寫好的demo 有需要的可以私信我

$(function() {
    // 創建對象
    const editor = new Squire(document.getElementById('demo'));

    //監聽粘貼事件
    editor.addEventListener('willPaste', function(data) {
        const content = $(data.fragment).text();
        // 停止粘貼
        data.preventDefault();
        // 轉換成text添加到富文本
        editor.insertHTML(content);
    });
    

    // 按鈕事件
    $('#btn').on('click', function() {
        if (editor.getSelectedText().length == 0) {
            return;
        }

        if ($(editor.getSelection().commonAncestorContainer.parentNode).hasClass('colour')) {
            editor.setTextColour('')
            return;
        }

        // 將選中的文字設置成紅色
        editor.setTextColour('red');
        //editor.insertHTML(`<span style="color: red;"><${editor.getSelectedText()}></span>`);

        // 聚合
        const content = editor.getHTML().replace(/<\/span><span class="colour" style="color:red">/g, '');
        editor.setHTML(content);
        
    });


    // 關鍵字事件
    $('#demo').on('click', '.colour', function() {
        alert('這是一個關鍵字點擊事件,當前關鍵字是:  '+$(this).text());
    });
    
       //$('#demo').on('mouseenter', '.colour', function() {
        //alert('這是一個關鍵字懸浮事件,當前關鍵字是:  '+$(this).text());
    //});

});

 

怎么引用都不會成功  由於我們的項目主要用的vue 框架(如果一定要用的話 應該要自己封裝一層)

 

第三種方法富文本編輯 wangeditor

  第二個框架的是完全滿足我們的需求了,但是我自己懶得再去封裝怎么在vue里面引用成功

  有專門的學習手冊:https://www.kancloud.cn/wangfupeng/wangeditor3/404586

  源碼開源:https://github.com/wangfupeng1988/wangEditor

  優點:滿足基本的富文本編輯,有專門的文檔,還在維護

  缺點:不可以自定義工具欄 方法沒有這么靈活 需要變通一下才可以實現某些功能

  

  我的實戰項目經驗 

  可以獲取當前選中文本,可以取消標記,可以獲取當前焦點最近的關鍵字。

  

 

   核心主要代碼

  

import E from 'wangeditor'  //引用

 var editor = new E(this.$refs.editor)

    editor.customConfig.onchange = (html) => {
      this.editorContent = editor.selection.getSelectionText()
      console.log(editor.selection.getSelectionText())
    }
    editor.customConfig.menus = [ //配置菜單
      'foreColor'
    ]
    editor.customConfig.colors = [ //配置顏色
        'red','#000'
    ]
    editor.customConfig.onfocus = function () {
      
    }
    editor.create()
    document.getElementById('btn2').addEventListener('click', function () {
        // 讀取 text
        let key = editor.selection.getSelectionText() //獲取選中內容

    }, false)

    document.getElementById('btn1').addEventListener('click', function () { //取消標記
        let test = editor.selection.getSelectionStartElem()[0].style.color
      if(test == 'red'){
        editor.selection.getSelectionStartElem()[0].style.color = '#000'
      }
    }, false)

    $('#editor').on('click', function() { //獲取最近關鍵字
      let texts = editor.selection.getSelectionStartElem()[0].innerText  
      
    });

 

 

fannie式總結

延伸思考 就是有很多中標記 這個標記的內容 都要對應儲存 不同顏色區分 可以取消標記這些之類的

還有web用富文本有一點點安全性問題哦

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM