2013-05-09 47 views
0

當我嘗試在webbrowser中運行javascript時,代碼會運行,但執行後會帶上右上角數字值(本例中爲「1000」)的白色頁面,帶我遠離網站,我以前C#WebBrowser運行Javascript - 返回帶有Javascript結果的空白頁 - 爲什麼?

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0]; 
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script"); 
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement; 
element.text = "function ScrollDown() { document.getElementsByClassName('scrollableitemclass').scrollTop = 1000 }"; 
head.AppendChild(scriptEl); 
webBrowser1.Document.InvokeScript("ScrollDown"); 

感謝您的幫助

+0

你要滾動到特定元素的Web瀏覽器的控制? – KF2 2013-05-09 13:25:53

+0

是的,該函數可以正常工作,但是執行完後,webbrowser會帶我進入一個白色頁面,並在右上角顯示一個數值(在本例中爲「1000」) – Ldg 2013-05-09 13:39:54

回答

1

您可以滾動到你的HTML Elemet與HtmlElement.ScrollIntoView

看看這個例子:

public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      webBrowser1.DocumentText = "<html><body><span class=\"cls\" id=\"el\"> </body></html>"; 
     } 

     void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
     { 
      //for element with id 
      webBrowser1.Document.GetElementById("el").ScrollIntoView(true); 
      //for element with spesific 
      foreach (HtmlElement el in webBrowser1.Document.All) 
      { 
       if (el.GetAttribute("ClassName") == "cls") 
       { 
        el.ScrollIntoView(true); 
       } 

      } 

     } 


    } 
相關問題