开发者

JS / JQuery execCommand problem

I am having trouble (complete) with execCommand so you help much appreciated - I have no doubt I am barking up the wrong tree but ..... anyway

I have a div like this

<div class="editable" id="editor" contenteditable="true"> 
    <2>Some text in here</h2> blah blah blah ...
</div>

That is "editable" i.e. document.designMode = 'on'; - it get's this "state" on focus. On blur it changes to document.designMode = 'off';

I have a "test button"

<input type="button" id="bold" value="Bold"> 

That when "clicked" makes the "highlighted text" bold - hence execCommand

So far I have something like this:

function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}


$('#bold').click(function(){
var selection = getSelected();
alert(selection);
});

The alert (bold click) does give me the highlighted/selected text but I cannot work out how to "turn it" bold. I guess I need to access the innerHTML or something?

Help mu开发者_运维问答ch appreciated - thanks in advance. OH and I do not want to use either an i-frame or a textarea


I strongly recommend using Rangy for dealing with text selection.

A cross-browser JavaScript range and selection library. It provides a simple standards-based API for performing common DOM Range and Selection tasks in all major browsers, abstracting away the wildly different implementations of this functionality between Internet Explorer and DOM-compliant browsers.

You can use the CSS Class Applier Module to bold the text (live demo).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜