使用引导程序&更改div中所选文本的颜色.选色器 [英] Change color of selected text in a div using bootstrap & color picker

查看:105
本文介绍了使用引导程序&更改div中所选文本的颜色.选色器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a div which has some long text

例如洛雷姆·伊普苏姆·多洛尔(Lorem ipsum dolor)坐立不安,奉献己任,埃伊斯莫德tempor indicidunt ut Labore et dolore magna aliqua sed做事."

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

我只想通过colorpicker(使用colpicker.js作为调色板)进行选择时更改"sit amet"的颜色.

I just want to change the color of "sit amet" upon selection through colorpicker(using colpicker.js for the color palette).

目前我所拥有的是:

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内容的颜色设置为颜色集.我只想更改突出显示的文本的颜色.

But the above code sets the color of the whole div content to the color set. I just want to change the color of the highlighted text.

推荐答案

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

You need to wrap selected text into some wrapepr, and unwrap it when unselected. Here is working example:

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>

运行代码段以查看其运行情况

Run code snippet to view it in action

这篇关于使用引导程序&amp;更改div中所选文本的颜色.选色器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆