使用引导程序和颜色选择器更改div中所选文本的颜色

我有一个div有一些长文本

例如,“Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。”

我只想通过colorpicker(使用colpicker.js作为调色板)更改“sit amet”的颜色。

目前我所拥有的是:

Html代码

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

脚本

 $('#editor').css('color', '#'+hex); 

但是上面的代码将整个div内容的颜色设置为颜色集。 我只是想改变突出显示文本的颜色。

您需要将选定的文本包装到某些wrappr中,并在取消选择时将其解包。 这是工作示例:

 function selectText(hexColor) { var selection = window.getSelection().getRangeAt(0); var selectedText = selection.extractContents(); var span = document.createElement('span'); span.style.backgroundColor = hexColor; span.className = 'selected-text'; span.appendChild(selectedText); selection.insertNode(span); } function unselectText(){ $('#text-box').find('.selected-text').contents().unwrap();; } $(document).on('mouseup', function () { selectText('#f90'); }); $(document).on('mousedown', function () { unselectText(); }); 
  
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

这只是选择’sit amet’字符串

jQuery的:

 $('#editor').replace('sit amet', 'sit amet'); $('span.col').css({'color': '#' + hex}); 

如果要为不固定的字符串设置样式:

 var string = 'your selected string'; $('#editor').replace(string, '' + string + ''); $('span.col').css({'color': '#' + hex});