开发者

Use execCommand on click

开发者 https://www.devze.com 2023-03-31 09:51 出处:网络
I am trying to make the currently selected node blue in font color. At the moment, I have the following code, which only makes text blue when highlighted and then clicked.

I am trying to make the currently selected node blue in font color. At the moment, I have the following code, which only makes text blue when highlighted and then clicked.

How would it be possible to make it so that when I click the text, the whole node changes its font color using execCommand?

$('[contenteditable]').bind('click', function() {
    currentSentence = window.getSelection().focusNode;
    caretPosition = window.getSelection().focusOffset;

    document.execCommand('ForeColor', false开发者_运维技巧, '000');
});


focusNode will only give you the container node of the focus of the selection, which is the most recently moved selection boundary. If that is what you want, you can save the selection, set the selection to encompass focusNode and then call document.execCommand(). If you need to restore the selection, that's a more difficult problem.

Note that none of this will work in IE < 9, which doesn't support window.getSelection() or Range and instead has a completely different API.

jsFiddle: http://jsfiddle.net/timdown/J6fAa/

Example code:

$('[contenteditable]').bind('click', function() {
    var sel = window.getSelection();
    var focusNode = sel.focusNode;
    var range = document.createRange();
    range.selectNode(focusNode);
    sel.removeAllRanges();
    sel.addRange(range);
    document.execCommand('ForeColor', false, '000');
});
0

精彩评论

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

关注公众号