开发者

Make selected text bold using javascript

I have a text in my markup:

<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit开发者_高级运维.
Vestibulum condimentum consectetur tellus, at bibendum felis ultrices eu.
Nullam nibh urna, euismod a blandit ut, fermentum a leo. Maecenas pharetra elementum fringilla.
Quisque condimentum, nibh quis elementum porttitor, magna libero malesuada dolor, ut feugiat tortor lectus ac turpis. Integer tristique molestie enim, sit amet commodo risus tempus non.
</div>

When user selects a text and presses CTRL+Enter I want to wrap the selected text with <b></b> tags. I got to getting the selected text, but cannot find how I can wrap it with the markup. Here is what I have:

function getSelectedText () {
    if (window.getSelection) {
        return window.getSelection ().toString ();
    }
    else {
        if (document.selection) {
            return document.selection.createRange ().text;
        }
    }
    return '';
}

$ (document).ready (function() {

    // User pressed a key 
    $ (document).keydown (function(e) {
        // is it CTRL+ENTER?
    if (e.which == 13 && e.ctrlKey) {
            alert('You have selected ' + getSelectedText ());
            // now I need to highlight the text I got
            // ????
    }
    });
});

Please note! A simple find/replace does not do, if a user selected a single 'a' letter which can be found 10 times in the text, I want to highlight the only 'a' he selected. I've studied range objects, but can't figure out how to achieve it, help me out, please.

Please see demo at jsfiddle.


Perhaps this can help you: http://code.google.com/p/rangy/

one of the examples is exactly what you're after.


You could use document.execCommand() for this. Here's my answer to a similar question: Javascript: how to un-surroundContents range


This works (in Chrome), but so long as it's only called once!

(running code at http://jsfiddle.net/HaD6k/)

$(document).keypress(function(e) {
    if (e.which == 13 && e.ctrlKey) {
        var s = getSelection();
        var i = s.baseOffset;
        var j = s.extentOffset;
        var t = $('div').text();
        var t0 = t.substring(0, i) + '<span class="b">' +
                 t.substring(i, j) + '</span>' +
                 t.substring(j);
        $('div').html(t0);
    }
});

The reason it only works once is because it modifies the DOM to add the tags, which means next time around the selection offsets and elements aren't contiguous. I'm still looking at that...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜