我有一个div有一些长文本
例如" Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。"
我只是想改变"坐下来的颜色。通过colorpicker选择(使用colpicker.js作为调色板)。
目前我所拥有的是:
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 :(得分:2)
这只是选择'sit amet'字符串
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});
答案 1 :(得分: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();
});
&#13;
<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>
&#13;
运行代码段以便在行动中查看