使用execCommand在UIWebView中使用Javascript文本编辑器

时间:2013-08-07 04:39:21

标签: javascript colors uiwebview font-face

为什么以下javascript命令无法设置UIWebView html富文本编辑器中使用的RGB十六进制的字体颜色?

RGB十六进制中的颜色更改为标准蓝色,黄色,红色等,例如:

[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.execCommand('forecolor', false, '#407ec9')"]];

在html中生成

<font color="#0000ff"> HELLO WORLD </font>

2 个答案:

答案 0 :(得分:0)

以下适用于Chrome,Safari,Firefox和Opera,甚至是Internet Explorer 9:

<input type="button" onclick="document.execCommand('forecolor', false, '#407ec9');" value="Change" />
<div contenteditable="true">Test</div>

http://jsfiddle.net/M5j8b/

它也适用于iOS 6中的Mobile Safari。

我的stringByEvaluatingJavaScriptFromString电话没有看到任何明显错误。我怀疑某些东西没有被正确地逃脱。

我会尝试在页面上创建一个简单的JavaScript函数,然后调用它:

function foo() {
    document.execCommand('forecolor', false, '#407ec9')
}

如果这不起作用,我怀疑是一个不同的问题。

答案 1 :(得分:0)

解决了它。这是我的解决方法:

NSString *color = @"#407ec9";
NSString *text = [self.webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];

[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.execCommand('insertHTML', false, '%@')", [NSString stringWithFormat:@"<font color=\"%@\">%@</font>", color, text]]];