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

前端之家收集整理的这篇文章主要介绍了使用Javascript获取webView内容的总高度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用一个UIWebView来显示 HTML字符串形式的内容,而不是一个高于iPhone屏幕的网站,而不需要滚动到webView本身,并将它留给父滚屏浏览.

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

(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

解决方案实际上有效吗?

当前(非工作)代码

[[[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:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    CGFloat contentHeight = webView.scrollView.contentSize.height;
    // ....
}

获取webView内容的总高度.

原文链接:https://www.f2er.com/js/153865.html

猜你在找的JavaScript相关文章