contenteditable="true"粘貼后的刪除內(nèi)容攜帶的樣式,設(shè)置為純文本

直接將此代碼放入js文件中,導(dǎo)出引用就好啦~

function textFormat (e) {
  e.preventDefault()
  var text
  var clp = (e.originalEvent || e).clipboardData
  if (clp === undefined || clp === null) {
    text = window.clipboardData.getData('text') || ''
    if (text !== '') {
      if (window.getSelection) {
        var newNode = document.createElement('span')
        newNode.innerHTML = text
        window.getSelection().getRangeAt(0).insertNode(newNode)
      } else {
        document.selection.createRange().pasteHTML(text)
      }
    }
  } else {
    text = clp.getData('text/plain') || ''
    if (text !== '') {
      document.execCommand('insertText', false, text)
    }
  }
}
export { textFormat }

引用處~

  • 若需要給每一個(gè)文本都添加'paste'的監(jiān)聽(tīng)事件,就要用到循環(huán),單個(gè)直接獲取當(dāng)前節(jié)點(diǎn)就可以了
  • !el.paste 這個(gè)是解決重復(fù)添加'paste'監(jiān)聽(tīng)事件,導(dǎo)致內(nèi)容重復(fù),如果沒(méi)有動(dòng)態(tài)添加文本功能,可以不要這個(gè)判斷
  • 代碼是vue的寫法,$nextTick是為了獲取到所有節(jié)點(diǎn)的內(nèi)容
import { textFormat } from '@/components/common.js'
this.$nextTick(() => {
        const textArr = document.querySelectorAll('.wn-text')
        textArr.forEach(el => {
          if (!el.paste) { 
            el.addEventListener('paste', e => {
              el.paste = true
              textFormat(e)
            })
          }
        })
      });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容