我有一个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'。
提前致谢!
答案 0 :(得分:0)
首先,line-height: '%d%%'px
应为line-height: '%d'px
。否则,您将构建类似line-height: '12%%'px
的内容,在呈现源时不会对其进行解析。
其次,stringValue
将类似于“12px”,因此如果不删除“px”,则无法直接将其转换为数字。