2014-12-30 62 views
1

我有一个具有一些长文本的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代码

<div id="editor">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div> 

脚本

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

但上面的代码将整个DIV内容的颜色颜色集合。我只想改变突出显示的文字的颜色。

+0

岂不是更好包围'由前坐amet'。跨类或id属性,并通过此引用更改颜色? – kamil09875

+0

您只能使用CSS(以及伪元素,例如':: first-letter',':: first-line')来定位元素,以定位他们首先必须使用的短语/词“sit amet”由元素包装,在客户端使用JavaScript或服务器端语言。 –

回答

1

你需要用选定的文本放入一些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(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="text-box">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. 
 
</div>

运行代码片段,查看它在行动

+0

感谢Vitalii,这个解决方案适合我。感谢您的快速回复 – Shikha

+0

我测试了一些,发现如果我重新选择了之前的选择,那么操作不会正确发生。如果我每次都插入跨度,它应该以某种方式覆盖我们添加的前一个跨度。我该怎么做? – Shikha

2

这只是选择了 '坐阿梅德' 字符串

jQuery的:如果你想要的风格,是不固定的字符串

$('#editor').replace('sit amet', '<span class="col">sit amet</span>'); 
$('span.col').css({'color': '#' + hex}); 

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

这将起作用,但我需要处理所选字符串例如:“sit amet”在div内容中出现多次的情况。我不能依赖所选的字符。我必须得到所选文本的位置,然后用彩色跨度替换它们。但非常感谢您的回复:) – Shikha