document.execCommand() FontSize in pixels?
How can I change font size to 30px (for example) using document.execCommand
?
This:
document.execCommand("fontSize", false, "30px");
doesn't work, because in 3rd argument of the function execCommand, it only allows me to input a value between and including 1 to 7.
It's a limitation of the FontSize
command. There are various options I can think of:
- You could use a CSS class instead and use the CSS class applier module of my Rangy library;
- You could use a hacky method, such as calling
document.execCommand("fontSize", false, "7");
and then finding the elements the command has created and changing them as required. See example: http://jsfiddle.net/S3ctN/. This obviously depends on there being no other<font>
elements with size 7 in the document and it also relies on the browser using<font>
elements for font size, which it seems they all do.
Function
var execFontSize = function (size, unit) {
var spanString = $('<span/>', {
'text': document.getSelection()
}).css('font-size', size + unit).prop('outerHTML');
document.execCommand('insertHTML', false, spanString);
};
Execute
execFontSize(30, 'px');
As second answer suggest just run some jquery after execcommand and replace the markup with your own.
Just replace elem with your element and edit the font-size with the desired value.
jQuery("font[size]", elem).removeAttr("size").css("font-size", "10px");