【问题标题】:UIWebView change line spacing for text in sourceUIWebView 更改源中文本的行距
【发布时间】:2012-05-28 15:02:56
【问题描述】:

我有一个 javascript 方法可以在 UIWebView 子类中传递给 stringByEvaluatingJavaScriptFromString:。

var head = document.getElementsByTagName('head')[0],
    style = document.createElement('style'),
    rules = document.createTextNode('* { line-height: 20px !important; }');
style.type = 'text/css';
if(style.styleSheet)
    style.styleSheet.cssText = rules.nodeValue;
else style.appendChild(rules);
head.appendChild(style);

我已将它添加到 stringByEvaluatingJavaScriptFromString: 方法中,只要我指定一个像素值,代码就可以工作。如果我使用像下面的代码这样的变量,它不会做任何事情。我做错了什么?

我正在使用 largeBool 来告诉我间距是否需要增加或减少。然后我设置最大值和最小值,并使用行高作为变量。

   - (void)changeLineSpacingLarger:(BOOL)largerBool {

    if (largerBool == YES) { // A+
        lineHeight = (lineHeight < 100) ? lineHeight +10 : lineHeight;
    }

    else if (largerBool == NO) { // A-
        lineHeight = (lineHeight > 20) ? lineHeight -10 : lineHeight;
    }

    NSString *jsString = [[NSString alloc] initWithFormat:@"var head = document.getElementsByTagName('head')[0], style = document.createElement('style'), rules = document.createTextNode('* { line-height: '%d%%'px !important; }'); style.type = 'text/css'; if(style.styleSheet) style.styleSheet.cssText = rules.nodeValue; else style.appendChild(rules); head.appendChild(style);", lineHeight];
    [self stringByEvaluatingJavaScriptFromString:jsString];
}

我也在使用 UIWebView 的 didFinishLoading 委托方法来保存当前的行距值。

- (void)updateLineSpacingValue {
    NSString *jsString = [[NSString alloc] initWithFormat:@"var element = document.getElementsByTagName('h1')[0], style = window.getComputedStyle(element), lh = style.getPropertyValue('line-height'); return lh;", textFontSize];
    NSString *stringValue = [self stringByEvaluatingJavaScriptFromString:jsString];

    lineHeight = [stringValue intValue];

    NSLog(@"Line Height: %i", lineHeight);
}

我得到的只是日志中的“0”。

提前致谢!

【问题讨论】:

    标签: javascript xcode ios5 uiwebview stringbyevaluatingjavascr


    【解决方案1】:

    首先,line-height: '%d%%'px 应该是 line-height: '%d'px。否则,您将构建类似line-height: '12%%'px 的内容,在渲染源代码时不会对其进行解析。


    其次,stringValue 将类似于“12px”,因此您无法在不删除“px”的情况下直接将其转换为数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      相关资源
      最近更新 更多