2014-12-30 28 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