开发者

How to change a colour of a word in jquery

How would i be able to select a word and change the colour of that one word?

e.g. add a span with style and chage the font colour.

Can someone lead me down the right path开发者_运维知识库 please.

Jquery

 function edit_addon (div_id) {    
    $("#"+div_id).attr ('contentEditable', true)
             .css ('color','#F00') 
             .css ('cursor','Text') 
             ; 

 } 

HTML

 <div id="34" ondblclick="javascript:edit_addon(34)">Editable Text</div>

Thank you,


The easiest way would be to dynamically add spans with the individual in the div and just change the color of the current span. Here's the basic idea:

$(".Editable").dblclick( function () {
    var words = $(this).text().split(" ");
    var result = "";
    for (var i=0; i<words.length; i++) {
        result.append("<span class='word'>" + words[i] + "</span>");
    }
    $(this).innerHTML = result;
}

#CSS

span.word:hover { color: #0f0; }


This should work for you. In general it is a lot easier to give your elements a class and then in your ready function (Seen here in short hand.) you can set up any dynamic aspects of the page.

<style type="text/css">
    .Word { color:#F00;cursor:text;padding:20px; }
</style>
<script type="text/javascript">
    $(function () {
        $("div.Editable").each(function () {
            var elem = $(this),
                text = elem.text(),
                words = text.split(" "),
                innerHtml = "<span>" + words.join("</span>&nbsp;<span>") + "</span>";
            elem.html(innerHtml);
        });
        $("div.Editable span").live("dblclick", function (evt) {
            $(this)
            .attr({ contentEditable: true })
            .addClass("Word");
        }).live("mouseout", function () {
            var elem = $(this);

            elem
            .attr({ contentEditable: false })
            .removeClass("Word");

            var text = elem.text(),
                words = text.split(" "),
                innerHtml = "<span>" + words.join("</span>&nbsp;<span>") + "</span>";

            elem.replaceWith($(innerHtml));
        });
    });
</script>

<div id="Editable34" class="Editable">
    Editable Editable Editable
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜