使用 Javascript 获取 webView 内容的总高度

Get total height of webView#39;s content using Javascript(使用 Javascript 获取 webView 内容的总高度)
本文介绍了使用 Javascript 获取 webView 内容的总高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我使用 UIWebView 来显示内容,以 HTML 字符串的形式——不是网站,高于 iPhone 的屏幕,无需在 webView 本身中滚动,离开到父 scrollView.

I'm using a UIWebView for displaying content, in the form of an HTML string – not a website, higher than the screen of the iPhone, without needing to scroll in the webView itself, leaving that to the parent scrollView.

为了实现这一点,我需要一种方法来获取总文档大小(包括可滚动区域)来设置 webView 的高度.我尝试了许多不同的 Javascript 解决方案:

To achieve this, I need a way to get the total document size, including the scrollable area, to set the webView's height. I have tried a number of different Javascript solutions:

(document.height !== undefined) ? document.height : document.body.offsetHeight // Returns height of UIWebView
document.body.offsetHeight // Returns zero
document.body.clientHeight // Returns zero
document.documentElement.clientHeight // Returns height of UIWebView
window.innerHeight // Returns height of UIWebView -2
document.body.scrollHeight // Returns zero

有没有真正有效的解决方案?

Is there a solution that actually works?

当前(非工作)代码:

[[[self.singlePost.contentText subviews] lastObject] setScrollEnabled:NO];
int content_height = [[self.singlePost.contentText stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"] intValue];
NSLog(@"Content_height: %d", content_height);
CGRect rect = self.singlePost.contentText.frame;
rect.size.height = content_height;
self.singlePost.contentText.frame = rect;

推荐答案

在 iOS 5.0 及更高版本中无需使用 Javascript - 您可以直接访问它的 scrollView:

There is no need to use Javascript in iOS 5.0 and up - you have direct, documented access to its scrollView:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    CGFloat contentHeight = webView.scrollView.contentSize.height;
    // ....
}

获取webView内容的总高度.

To get the total height of the contents of the webView.

这篇关于使用 Javascript 获取 webView 内容的总高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

UIButtons at the bottom of UIScrollView not working(UIScrollView 底部的 UIButtons 不起作用)
Bounds automatically changes on UIScrollView with content insets(UIScrollView 上的边界自动更改,带有内容插图)
iOS5 UITapRecognizer for UIScrollView interfering with buttons. How to fix?(用于 UIScrollView 的 iOS5 UITapRecognizer 干扰按钮.怎么修?)
How to Cancel Scrolling in UIScrollView(如何在 UIScrollView 中取消滚动)
How can i add a activity indicator below the UITableView?(如何在 UITableView 下方添加活动指示器?)
NSURLRequest won#39;t fire while UIScrollView is scrolling(NSURLRequest 在 UIScrollView 滚动时不会触发)