問題描述
我使用 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 內容的總高度的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!