document.execCommand() 的字体大小单位是像素吗?

21

我如何使用document.execCommand将字体大小更改为30px(例如)?

这样做:

document.execCommand("fontSize", false, "30px");

无法正常工作,因为在函数execCommand的第三个参数中,只允许输入1到7之间(包括1和7)的值。

10个回答

21

这是FontSize命令的一个限制。我想到了几个选项:

  • 您可以使用CSS类,然后使用我的Rangy库中的CSS类应用程序模块;
  • 您可以使用一种hack方法,例如调用document.execCommand("fontSize", false, "7");,然后查找命令创建的元素并根据需要更改它们。请参见示例:http://jsfiddle.net/S3ctN/。显然,这取决于文档中没有其他大小为7的<font>元素,并且它也依赖于浏览器使用<font>元素来设置字体大小,似乎所有浏览器都会这样做。

11

功能

var execFontSize = function (size, unit) {
    var spanString = $('<span/>', {
        'text': document.getSelection()
    }).css('font-size', size + unit).prop('outerHTML');

    document.execCommand('insertHTML', false, spanString);
};

执行

execFontSize(30, 'px');

这在Mozilla Firefox中有效,但在IE中无效。 - Thomas Williams
它会删除选择范围内的任何其他HTML/CSS! - Xahed Kamal

9

只需使用CSS覆盖它:

font[size='7']{
    font-size: 20px; // or other length unit
}

如果你使用 scss ,你可以使用循环生成所有从 1 到 7 的选择器:

@for $i from 1 to 7 {
    font[size='#{$i}']{
        font-size: $i * 2vw
    }
}

非常简单而且不错!谢谢! - Ritesh Jagga

7

如第二个答案所建议的那样,在execcommand之后运行一些jQuery,用您自己的标记替换标记。

只需将elem替换为您的元素,并使用所需值编辑字体大小。

jQuery("font[size]", elem).removeAttr("size").css("font-size", "10px");

6
这里有一个比许多提议更好的解决方案,因为它直接从所选文本中获取要更改字体大小的元素。因此,它不必浏览DOM以获取正确的元素,并且不需要禁止使用特定的fontSize(如已被建议的第一个选项和其他答案中的7)。
function changeFont() {
    document.execCommand("fontSize", false, "7");
    var fontElements = window.getSelection().anchorNode.parentNode
    fontElements.removeAttribute("size");
    fontElements.style.fontSize = "30px";
}

简而言之,我们只需使用execCommand将选择内容包裹在一个span中,以便随后调用getSelection()时将高亮的span作为父级。然后,我们只需向该标识的span添加fontSize样式。
在这里,由于我们使用了fontSize命令,它不会被包装在中,而是被包装在中。
但这是一种通用方法,可以与execCommand的任何命令一起使用,后者仅被用作一种方便的方式,即使在不同的元素之间也可以包装所选内容。
这里有一个实时DEMO

它是否与编辑器的撤销/重做功能很好地配合?我进行了粗略尝试,它可以正常工作。 - asinix
1
是的,这很容易实现,你只需要用其内容(innerHTML)替换span(或在这种情况下的font)。假设你有<font style="font-size: 40px;">m</font>,你只需要替换它的innerHTML或innerText,即“m”。 - Bonjour123
很高兴能帮上忙 ;) - Bonjour123

5
我是一名有用的助手,可以为您翻译以下内容:

这只是我的解决方案。它可以在Chrome浏览器上运行。这段代码来自于一个中国网站(易企秀)。

首先

document.execCommand("styleWithCSS", 0, true);
document.execCommand('fontSize', 0, '12px');

那么

jQuery.find('[style*="font-size: -webkit-xxx-large"],font[size]').css("font-size", "12px")

注意:传递给execCommand的字体大小必须至少为“12px”及以上。


非常感谢你。 - Anbhu

2

$(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>


1

我在纯JavaScript中找到了一种解决方案,适用于具有自定义HTML(颜色、字体系列)的多行。

获取文档的选择。解析选择并保存其中的HTML标记。然后使用document.execCommand将所选的HTML插入具有内联样式的div中。当使用document.execCommand('insertHTML',false,html)时,还可以在所见即所得编辑器中获得撤消的好处。

这是该函数:

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);
}

希望它有所帮助。

1
最好的解决方案我见过的。
function onFS() {
const size = prompt("Enter font size:")
const txt = document.getSelection()

document.execCommand("insertHTML", false, `<font style=font-size:${size}px;>${txt}</font>`)
}

-1
如果您想为编辑器设置默认字体大小,则可以执行以下操作。
您必须使用“content_style”选项配置TinyMCE CSS。
例如,以下配置将将默认字体大小设置为12pt。
tinymce.init({
  /* ... */ content_style: "body {font-size: 12pt;}",
});

请记住,这些样式仅适用于编辑器内部的内容 - 如果您希望在发布的内容中也是默认大小,则必须确保相同的样式应用于那些已发布的页面。

希望能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接