【问题标题】:Javascript Text Editor in UIWebView using execCommand使用 execCommand 在 UIWebView 中的 Javascript 文本编辑器
【发布时间】:2013-08-07 04:39:20
【问题描述】:

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

RGB hex 中的颜色更改为标准的蓝色、黄色、红色等,例如:

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

在 html 中生成

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

【问题讨论】:

    标签: javascript colors uiwebview font-face


    【解决方案1】:

    以下内容适用于 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')
    }
    

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

    【讨论】:

    • 对不起,我在 iOS UIWebView 中使用了那个 JS 命令。我试图简化我的问题,现在已经编辑它以在 iOS 环境中正确形成问题。这似乎是 UIKit 的问题。
    • 不起作用。我正在发布解决方法的答案。感谢您的帮助!
    • @chongsj 奇数。它应该有。您的页面中必须有其他内容。好吧,很高兴你想到了什么
    【解决方案2】:

    解决了。这是我的解决方法答案:

    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]]];
    

    【讨论】:

    • 如果可能的话,我建议使用除已弃用的&lt;font&gt; 标签之外的其他东西。 &lt;span style="..."&gt; 会更好。
    • 也许如果你的 contenteditable 属性为 true 那么它会起作用
    猜你喜欢
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多