在使用WebView加载HTML内容时,我们有时需要直接跳转到页面中的某个特定锚点。
loadDataWithBaseUrl
方法可以在加载数据的同时设置一个基础的URL,此方法非常适用于处理这种情况。
loadDataWithBaseUrl
方法
:通过此方法加载HTML内容,并设置适当的基本URL。
假设你有以下的HTML内容:
html<html> <title>示例页面</title> </head> <h1 id="top">页面顶部</h1> <p>一些介绍性的内容...</p> <h2 id="anchor-point">重要的锚点</h2> <p>你想直接跳转到这里。</p> </body> </html>
你希望在WebView中加载此HTML,并直接跳转到ID为
anchor-point
的部分。
Java代码示例
javaWebView webView = findViewById(R.id.webview); String htmlContent = "<html><head><title>示例页面</title></head><body>..." + "<h1 id=\"top\">页面顶部</h1>" + "<p>一些介绍性的内容...</p>" + "<h2 id=\"anchor-point\">重要的锚点</h2>" + "<p>你想直接跳转到这里。</p>" + "</body></html>"; String baseUrl = "file:///android_asset/"; // 加载HTML内容 webView.loadDataWithBaseURL(baseUrl, htmlContent, "text/html", "UTF-8", null); // 使用JavaScript跳转到锚点 webView.loadUrl("javascript:window.location.hash='#anchor-point'");