在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ javascript 如何獲取光標(biāo)選取的值并替換?

javascript 如何獲取光標(biāo)選取的值并替換?

問題:如何實(shí)現(xiàn)類似富文本編輯器的文本選中并替換值得功能?

 var word = window.getSelection?window.getSelection():document.selection.createRange();
 alert(word); 

使用以上api可以實(shí)現(xiàn)獲取選取的值,但是如何得到選取的值具體位置并且替換呢?

回答
編輯回答
我甘愿

有個(gè)選擇內(nèi)容加版權(quán)聲明的常見效果。。。感覺和你這個(gè)需求類似。。。

$('body').on('copy', function (e) {

  if (typeof window.getSelection == 'undefined') {

    return;
  }

  var body_element = document.body,
      selection = window.getSelection();

  if (('' + selection).length < 30) {

    return;
  }

  var newdiv = document.createElement('div');

  newdiv.style.position = 'absolute';

  newdiv.style.left = '-99999px';

  body_element.appendChild(newdiv);

  newdiv.appendChild(selection.getRangeAt(0).cloneContents());

  if (selection.getRangeAt(0).commonAncestorContainer.nodeName == 'PRE') {

    newdiv.innerHTML = '<pre>' + newdiv.innerHTML + '</pre>';
  };

  newdiv.innerHTML += '<br />著作權(quán)歸作者所有。<br />商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。<br />原文: <a href="' + location.href + '">' + location.href + '</a> ? abcde.com';

  selection.selectAllChildren(newdiv);

  window.setTimeout(function () {

    body_element.removeChild(newdiv);
  }, 200);
});
2018年8月4日 17:17
編輯回答
故人嘆
window.getSelection().baseNode.data='改變的內(nèi)容'
2018年5月21日 19:33