【问题标题】:UIWebView change line spacing textUIWebView 更改行距文本
【发布时间】:2012-05-27 16:31:13
【问题描述】:

我正在寻找一种 javascript 方法或更改 UIWebView 中文本行距的方法。

有什么想法吗?

编辑:

Evan 已经回答了上述问题,但我还有另一个关于同一主题的问题。

如何查询当前行距值的来源?

【问题讨论】:

  • 来源来自哪里(网络服务器,本地文件)?你能修改它吗?
  • 这是一个浏览器类型的应用程序。全部来自互联网,我想在内容加载到 UIWebView 后更改文本的行距。

标签: javascript xcode ios5 uiwebview


【解决方案1】:

您需要通过调用stringByEvaluatingJavaScriptFromString: 将javascript 注入UIWebView 的源代码。

Javascript:

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

Objective-C(可能在webViewDidFinishLoading:):

NSString *js = /* The javascript above in a string */
[webView stringByEvaluatingJavaScriptFromString:js];

要检索页面上第一个 h1 元素的 line-height 值:

Javascript:

var element = document.getElementsByTagName('h1')[0],
    style = window.getComputedStyle(element),
    lh = style.getPropertyValue('line-height');
return lh;

目标-C:

NSString *js = /* The javascript above in a string */
NSString *lineHeight = [webView stringByEvaluatingJavaScriptFromString:js];

【讨论】:

  • 只是想澄清这一行“line-height: 20px !important;” - 20px 可以用变量替换,对吧? !important 是什么意思?
  • 是的,“20px”只是我选择的一个值。您可以使用[NSString stringWithFormat:...] 将其插入到字符串中。 "!important" 用于覆盖页面上已经存在的其他 line-height 样式。
  • 还有一个问题,如何从源代码中获取当前行高?
  • 这取决于它应用到的元素。对于不同的ph1 等元素,它可能会有所不同。
  • 为了论证起见,假设为 h1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
相关资源
最近更新 更多