简体   繁体   English

pasteHTML 之前的 document.execCommand 不起作用

[英]document.execCommand before pasteHTML not working

I'm developing a rich text editor.我正在开发一个富文本编辑器。

If i document.execCommand ('bold', false, null) before pasteHTML to insert some text, it does not work.如果我在pasteHTML之前使用document.execCommand ('bold', false, null)插入一些文本,则它不起作用。 I want to send command 'bold' and then insert some special text with pasteHTML and make that text bold.我想发送命令“粗体”,然后使用 pasteHTML 插入一些特殊文本并使该文本变为粗体。

I'm using bold as example, but can be any execCommand.我以粗体为例,但可以是任何 execCommand。

Any help?有什么帮助吗?

I think you might be better off creating a span or div and setting its style to bold or whatever you want then inserting that.我认为你最好创建一个 span 或 div 并将其样式设置为粗体或任何你想要的然后插入它。 Browser differences mean it gets very messy otherwise.浏览器的差异意味着否则它会变得非常混乱。 Here's an example of what I mean:这是我的意思的一个例子:

http://jsfiddle.net/nsfPN/ http://jsfiddle.net/nsfPN/

function pasteBoldHtmlAtCaret(html) {
    pasteHtmlAtCaret('<span style="font-weight: bold;">' + html + '</span>');
}

The other way would be to select the inserted html, send the command to set it to bold (if it isn't bold already) then set the cursor position to after the inserted html.另一种方法是选择插入的 html,发送命令将其设置为粗体(如果它不是粗体),然后将光标位置设置为插入的 html 之后。 Then you'd need to make sure that any text typed/inserted after that wasn't also bold (or ensure it is if you want that).然后,您需要确保在此之后键入/插入的任何文本也不是粗体(或者如果需要,请确保它是粗体)。 All these steps would be subject to the vagaries of different browser implementations.所有这些步骤都将受到不同浏览器实现的变幻莫测。

EDIT : If all you need to do is insert some text that takes on the current style and you don't need to support certain older browsers then you can just use the insertText command like so:编辑:如果您需要做的只是插入一些采用当前样式的文本,并且您不需要支持某些较旧的浏览器,那么您可以像这样使用 insertText 命令:

function pasteTextWithStyle(html) {
    if (document.queryCommandEnabled('insertText')) {
        document.execCommand('insertText', false, html);
    } else {
        // TODO: If the browser doesn't support insertText,
        // check current styles and manually apply them...
    }
}

See: http://jsfiddle.net/2Ljfj/ I'm not able to test it on the iPhone at the moment but it's been supported in webkit for awhile at least so it should work.请参阅:http: //jsfiddle.net/2Ljfj/目前我无法在 iPhone 上对其进行测试,但它至少在 webkit 中得到了一段时间的支持,因此它应该可以工作。

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

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