簡體   English   中英

UIWebView更改源中文本的行距

[英]UIWebView change line spacing for text in source

我有一個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告訴我間距是否需要增加或減小。 然后,我設置max和min,並使用行高作為變量。

   - (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”。

提前致謝!

首先, line-height: '%d%%'px應該是line-height: '%d'px 否則,您將構建類似於line-height: '12%%'px東西line-height: '12%%'px ,渲染源時將不會對其進行解析。


其次, stringValue類似於“ 12px”,因此您不能在不刪除“ px”的情況下將其直接轉換為數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM