jQuery如何应用CSS到选定的文本 [英] jQuery How do i apply CSS to selected text

查看:185
本文介绍了jQuery如何应用CSS到选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将CS​​S应用于所选文字。我试过以下,它不工作。我使用的是Firefox。

I'm trying to apply CSS to selected text. I tried the following and it doesn't work. I'm using Firefox.

$(document).keyup(function(){
savedRange = selection.getRangeAt(0);
$(savedRange).wrap('<span style="color:red"></span>');
});

我也试过了

savedRange = selection.getRangeAt(0);
$(savedRange).css('color', 'red');

我可以使用exec命令通过contentEditable执行此操作,但execcommand应用html标签,而不是内联样式。例如:< font /> 而不是 style =font ..。我需要应用内联样式,而不是废弃的html标记。我想使用jQuery css()属性来应用样式。

I can do this with contentEditable using execcommand, but execcommand applies html tags rather then inline styles. ex: <font/> instead of style="font..". I need to apply inline style and not deprecated html tags. I would like to use the jQuery css() property to apply styles.

推荐答案

我建议您使用我的 Rangy 图书馆的CSS类应用程序模块为了这。它适用于所有主要的浏览器和任何选择。它还将打开和关闭CSS类。

I'd recommend the CSS class applier module of my Rangy library for this. It works in all major browsers and for any selection. It will also toggle CSS classes on and off.

这是另一个问题的示例:

Here's an example from another question: How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?

示例:

<style type="text/css">
    span.red {
        color: red;
    }
</style>
<script type="text/javascript">
    var redApplier;

    window.onload = function() {
        rangy.init();
        redApplier = rangy.createCssClassApplier("red", true);
    };

    function makeSelectionRed() {
        redApplier.applyToSelection();
    }
</script>

UPDATE

如果使用类不是一个选项,你仍然可以使用变体,虽然它有点迂回:你可以使用Rangy来应用一个类,然后使用jQuery找到与这个类的跨度,并添加你的CSS到每个。例如:

If using classes isn't an option, you could still use a variation on this, although it's slightly roundabout: you could use Rangy to apply a class, and then use jQuery to find spans with this class and add your CSS to each. Here's an example:

function makeSelectionRed() {
    var randomCssClass = "rangyTemp_" + (+new Date());
    var classApplier = rangy.createCssClassApplier(randomCssClass, true);
    classApplier.applyToSelection();

    // Now use jQuery to add the CSS colour and remove the class
    $("." + randomCssClass).css({"color": "red"}).removeClass(randomCssClass);
}

jsFiddle: http://jsfiddle.net/z2mdw/2/

jsFiddle: http://jsfiddle.net/z2mdw/2/

这篇关于jQuery如何应用CSS到选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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