繁体   English   中英

Chrome 中的 document.execCommand('heading' ..')

[英]document.execCommand('heading' ..') in Chrome

我正在尝试使用 MDN here 中描述的富文本编辑命令功能

这个 API 看起来相当简单。 选择一些文本,然后执行命令,它将用它包装内容。 很酷的东西!

在 Firefox (Aurora) 中,这很好用:

document.execCommand('heading', false, 'H1');

但是,Chrome 中的相同命令不返回任何内容。 这不是在 Chrome 中以相同的方式(或根本)实现的吗?

谢谢!

恐怕 Chrome 还不支持标题命令。 您可以在 Chrome 中查看此页面以获取可用命令: http : //tifftiff.de/contenteditable/compliance_test.html

您正在寻找的是formatBlock命令,如下所示:

document.execCommand('formatBlock', false, '<h1>');

有一种方法可以只修改选定的文本。

borto = {
            tmpEl: document.createElement('div'),
            /* create element like in jquery with string <tag attribute1 attribute2 /> or <tag attribute1></tag> */
            htmlToDom: function(htmlEl){
                borto.tmpEl.innerHTML = htmlEl;
                return borto.tmpEl.children[0]
            },
            wrapSelection: function(htmlEl){
                var sel = window.getSelection();
                // In firefox we can select multiple area, so they are multiple range
                for(var i = sel.rangeCount;i--;){
                    var wrapper = borto.htmlToDom(htmlEl)
                    var range = sel.getRangeAt(i);
                    wrapper.appendChild(range.extractContents());
                    range.insertNode(wrapper);
                }
            }
        }

例如将所选文本放入 h1 标签:

borto.wrapSelection('<h1/>')

https://jsfiddle.net/31pncq01/标题 h1、h2 的示例

你可以用三个动作来创造它,就像这样......

var S=window.getSelection();

document.execCommand('delete',false,'');

document.execCommand('insertHTML',false,'<h1>'+S+'</h1>');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM