我需要加载WebView并需要根据div类修改CSS,在我的情况下我需要定位到innerClass
。例如,我在WebView中有这个代码:
<div class="myClass">
<div class="innerClass">
Some Text here.
</div>
</div>
如何将innerClass
设为display:none
?
以下是MainActivity.java
中的代码:
final WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("https://xxxx.com");
答案 0 :(得分:1)
你可以使用这样的javascript代码:
mWebView.setWebChromeClient(new WebChromeClient()); // for alert
mWebView.loadUrl("javascript:alert('hello world')");
您可以通过以下方式实现目标:
mWebView.loadUrl("javascript:document.getElementsByClassName('innerClass')[0].style.display = 'none'");
这是完整的例子:
MainActivity.java
public class MainActivity extends Activity {
private WebView mWebView;
private boolean isVisible = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebChromeClient(new WebChromeClient()); // for alert, anyway.
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
String htmlString = "<html><div class=\"myClass\">\n" +
"myClass text here" +
" <div class=\"innerClass\">\n" +
" Some Text here.\n" +
" </div>\n" +
"</div>" +
"</html>";
mWebView.loadData(htmlString, "text/html; charset=utf-8", null);
mWebView.loadUrl("javascript:alert('hello world')");
}
public void toggle(View view) {
if (isVisible) {
mWebView.loadUrl("javascript:var d = document.getElementsByClassName('innerClass')[0]; d.setAttribute(\"style\",\"display:none;\");");
} else {
mWebView.loadUrl("javascript:var d = document.getElementsByClassName('innerClass')[0]; d.setAttribute(\"style\",\"display:visible;\");");
}
isVisible = !isVisible;
}
}
activity_main.xml中
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="runJavascript"
android:text="Click"/>
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>