2017-11-18 222 views
0

我需要加載WebView,並需要修改基於div類的CSS,在我的情況下我需要將目標設置爲innerClass。例如,我有這樣的代碼中的WebView:如何在Android WebView中定位類名?

<div class="myClass"> 
    <div class="innerClass"> 
    Some Text here. 
    </div> 
</div> 

如何設置innerClassdisplay:none

這裏是我的代碼在MainActivity.java

final WebView myWebView = (WebView) findViewById(R.id.webview); 
WebSettings webSettings = myWebView.getSettings(); 
webSettings.setJavaScriptEnabled(true); 
myWebView.loadUrl("https://xxxx.com"); 
+0

爲什麼downvote?是否清楚我的問題? – Nere

回答

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> 
+0

謝謝..但不工作... huhu – Nere

+0

警報也不工作.. – Nere

+0

我很抱歉讓你困惑。我編輯了代碼,並測試了此代碼。 –