【问题标题】:Change color of selected text in a div using bootstrap & color picker使用引导程序和颜色选择器更改 div 中选定文本的颜色
【发布时间】:2015-02-26 14:24:43
【问题描述】:

我有一个有一些长文本的 div

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

我只想在通过颜色选择器(使用 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内容的颜色设置为颜色集。我只想更改突出显示文本的颜色。

【问题讨论】:

  • 用ex包围sit amet不是更好吗?使用 class 或 id 属性跨越并通过此引用更改颜色?
  • 您只能使用 CSS 定位元素(和伪元素,例如 ::first-letter ::first-line),以定位首先必须被包装的短语/单词“sit amet”通过元素,在客户端使用 JavaScript 或服务器端语言。

标签: jquery twitter-bootstrap color-picker


【解决方案1】:

这只是选择'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});

【讨论】:

  • 这会起作用,但我需要处理所选字符串(例如:“sit amet”)在 div 内容中多次出现的情况。我不能依赖所选的字符。我必须获取所选文本的位置,然后用彩色跨度替换它们。不过还是谢谢你的回复:)
【解决方案2】:

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

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>

运行代码 sn-p 以查看它的实际效果

【讨论】:

  • 感谢 Vitalii,这个解决方案对我有用。感谢您的快速回复
  • 我又测试了一些,发现如果我重新选择之前的选择,那么动作就不会正确发生。如果我每次都插入一个跨度,它应该以某种方式覆盖我们添加的前一个跨度。我该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2021-08-08
  • 1970-01-01
  • 2012-04-16
  • 2014-05-16
相关资源
最近更新 更多