通过下面的代码,我尝试将 HTML 加载到 WKWebview 中,然后将其滚动到特定元素。
let url = Bundle.main.url(forResource: "TestHTML", withExtension: "html")!
myWebView.loadFileURL(url, allowingReadAccessTo: url)
myWebView.evaluateJavaScript("document.getElementById('4').scrollIntoView(true);") {[weak self] (result, error) in
print("result: \(result)")
print (error)
}
但是,当我运行它时,页面会加载,滚动到该部分,然后跳回页面顶部。
我还尝试设置 scrollView
的 contentOffset
,导致完全相同的问题
最佳答案
您应该在 webview 委托(delegate)方法中编写 JavaScript 评估代码didFinish 导航
extension WebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(webView.url)")
webView.evaluateJavaScript("document.getElementById('4').scrollIntoView(true);") { (any, error) in
dump(error)
print(any)
}
}
}
并且不要忘记设置 webview delgate
myWebView.navigationDelegate = self
关于javascript - WKWebView中使用scrollIntoVIew跳转到页面顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56777461/