Javascript document.execCommand() FontSize 以像素为单位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5868295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
document.execCommand() FontSize in pixels?
提问by bordeux
How can I change font size to 30px (for example) using document.execCommand
?
如何使用 将字体大小更改为 30px(例如)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.
不起作用,因为在函数 execCommand 的第三个参数中,它只允许我输入一个介于 1 到 7 之间(包括 1 到 7)的值。
回答by Tim Down
It's a limitation of the FontSize
command. There are various options I can think of:
这是FontSize
命令的限制。我能想到的有多种选择:
- You could use a CSS class instead and use the CSS class appliermodule of my Rangylibrary;
- 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.
- 您可以改用 CSS 类并使用我的Rangy库的CSS 类应用程序模块;
- 您可以使用一种hacky 方法,例如调用
document.execCommand("fontSize", false, "7");
然后查找命令创建的元素并根据需要更改它们。参见示例:http: //jsfiddle.net/S3ctN/。这显然取决于<font>
文档中没有其他大小为 7 的元素,并且还依赖于浏览器使用<font>
字体大小的元素,似乎他们都这样做。
回答by Roman S
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');
回答by Benjamin Favre
As second answer suggest just run some jquery after execcommand and replace the markup with your own.
作为第二个答案,建议在 execcommand 之后运行一些 jquery 并用您自己的标记替换标记。
Just replace elem with your element and edit the font-size with the desired value.
只需用您的元素替换 elem 并使用所需的值编辑字体大小。
jQuery("font[size]", elem).removeAttr("size").css("font-size", "10px");
回答by Bonjour123
Here is a better solution than many proposed here, as it directly gets the element on which to change the font size from the selected text.
这是一个比此处提出的许多解决方案更好的解决方案,因为它直接从所选文本中获取要更改字体大小的元素。
As a consequence, it doesn't have to browse the DOM to get the right element, and doesn't require to ban the use of a specific fontSize (7, as suggested in the first option of the accepted answer, and in other answers).
因此,它不必浏览 DOM 来获取正确的元素,并且不需要禁止使用特定的 fontSize(7,如已接受答案的第一个选项中所建议的,以及在其他答案中)。
function changeFont() {
document.execCommand("fontSize", false, "7");
var fontElements = window.getSelection().anchorNode.parentNode
fontElements.removeAttribute("size");
fontElements.style.fontSize = "30px";
}
In summary we just use execCommand to wrap the selection with a span, so that the subsequent call to getSelection() whill have the highlighted span as parent . Then we just add the fontSize style to that identified span.
总之,我们只是使用 execCommand 用 span 包装选择,以便随后对 getSelection() 的调用将突出显示的 span 作为 parent 。然后我们只需将 fontSize 样式添加到该标识的跨度。
Here, as we are using the fontSize command, it won't be wrapped inside a <span>
, but inside a <font>
.
在这里,当我们使用 fontSize 命令时,它不会被包裹在 a 中<span>
,而是包裹在 a 中<font>
。
But this is a generic method which can work with any command of execCommand, the latter being used just as a convenient manner to wrap the selected contents even among different elements.
但这是一个通用方法,可以与 execCommand 的任何命令一起使用,后者只是作为一种方便的方式来包装所选内容,即使在不同的元素之间。
Here is a live DEMO
这是一个现场演示
回答by soli
Just override it with css:
只需用 css 覆盖它:
font[size='7']{
font-size: 20px; // or other length unit
}
Or if you use scss you could use a loop to generate all selectors from 1 to 7:
或者,如果您使用 scss,您可以使用循环生成从 1 到 7 的所有选择器:
@for $i from 1 to 7 {
font[size='#{$i}']{
font-size: $i * 2vw
}
}
回答by u6224545
it just my solutions.it works with chrome. the code was find in a china website(eqxiu).
它只是我的解决方案。它适用于 chrome。该代码是在china网站(eqxiu)中找到的。
first
第一的
document.execCommand("styleWithCSS", 0, true);
document.execCommand('fontSize', 0, '12px');
then
然后
jQuery.find('[style*="font-size: -webkit-xxx-large"],font[size]').css("font-size", "12px")
note: the fontsize pass to execCommand must be at least '12px' and above.
注意:传递给 execCommand 的 fontsize 必须至少为 '12px' 及以上。
回答by surinder singh
$(document).ready(()=>{
var activeFontSize = 30;
var oDoc = document.getElementById("editor");
var style = document.createElement("style");
document.body.appendChild(style);
function setFontSize(value){
$editor.focus();
document.execCommand("fontsize", false, 20);
activeFontSize = value;
createStyle();
updateTags();
}
function updateTags(){
var fontElements = oDoc.getElementsByTagName("font");
for (var i = 0, len = fontElements.length; i < len; ++i) {
if (fontElements[i].size == "7") {
fontElements[i].removeAttribute("size");
fontElements[i].style.fontSize = activeFontSize+"px";
}
}
}
function createStyle(){
style.innerHTML = '#editor font[size="7"]{font-size: '+activeFontSize+'px}';
}
function updateToolBar(args){
$fontSize.val(args.fontsize);
}
var $fontSize = $("#fontSize");
var $editor = $("#editor");
$fontSize.on("change", ()=>{
setFontSize($fontSize.val())
})
$editor.on("keyup", ()=>{
updateTags();
})
//var i = 0;
$editor.on("keyup mousedown", (e)=>{
//i++;
//console.log("e.target", e.target)
try{
var fontsize = $(window.getSelection().getRangeAt(0).startContainer.parentNode).css("font-size")
fontsize = fontsize.replace("px", "");
//document.execCommand("insertHTML", false, '<span class="font-size-detector'+i+'">X</span>');
//var fontsize = $(e.target).css("font-size")//$editor.find(".font-size-detector"+i).css("font-size");
//document.execCommand("undo", false, false);
//$editor.focus();
//console.log("fontsize", fontsize)
updateToolBar({fontsize})
}catch(e){
console.log("exception", e)
}
})
oDoc.focus();
setFontSize(30);
})
.editor-box{box-shadow:0px 0px 1px 2px #DDD;max-width:500px;margin:0px auto;}
.editor-tools{padding:20px;box-shadow:0px 2px 1px 0px #DDD}
.editor-tools button{user-select:none;}
#editor{height:200px;margin:10px 0px;padding:10px;font-size:14px;}
#editor:focus{outline:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="editor-box">
<div class="editor-tools">
<label>Font Size: </label>
<select id="fontSize" >
<option value="10">10px</option>
<option value="12">12px</option>
<option value="14">14px</option>
<option value="20">20px</option>
<option value="22">22px</option>
<option value="30" selected="true">30px</option>
<option value="35">35px</option>
<option value="40">40px</option>
<option value="45">45px</option>
<option value="50">50px</option>
</select>
</div>
<div id="editor" contenteditable="true">Hello, this is some editable text</div>
</div>
回答by Cristi Ghinea
Found a solution in pure JavaScript that works for multiple lines with custom HTML (colors, font families).
在纯 JavaScript 中找到了一个解决方案,该解决方案适用于具有自定义 HTML(颜色、字体系列)的多行。
Get the selection of the document. Parse the selection and save the html tags from it. Then with document.execCommand insert the selected html inside a div that has inline style. Also a benefit when using document.execCommand('insertHTML', false, html) is that you get undo in WYSIWYG editor.
获取文档的选择。解析选择并从中保存 html 标签。然后使用 document.execCommand 将选定的 html 插入具有内联样式的 div 中。使用 document.execCommand('insertHTML', false, html) 的另一个好处是您可以在 WYSIWYG 编辑器中撤消。
This is the function:
这是函数:
function fontSize(size) {
var sel = document.getSelection(); // Gets selection
var selectedHtml = "";
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
const children = container.getElementsByTagName("*")
for(let child of children) {
if(child.style.fontSize) {
child.style.fontSize = `${size}px`
}
}
selectedHtml = container.innerHTML;
}
let html = `<div style="font-size: ${size}px;">${selectedHtml}</div>`
document.execCommand('insertHTML', false, html);
}
Hope it helps.
希望能帮助到你。