Sdílet prostřednictvím


Postupy: Změna stylů u elementu ve spravovaném objektovém modelu dokumentu HTML

Styly ve formátu HTML můžete použít k řízení vzhledu dokumentu a jeho prvků. HtmlDocument a HtmlElement podporují vlastnosti Style, které přijímají řetězce stylů v následujícím formátu:

name1:value1;...;nameN:valueN;

Tady je DIV s řetězcem stylu, který nastaví písmo na Arial a veškerý text na tučný:

<DIV style="font-face:arial;font-weight:bold;">
Hello, world!
</DIV>

Problém s manipulací se styly pomocí vlastnosti Style spočívá v tom, že může být nesnadné přidávat a odebírat jednotlivá nastavení stylu z řetězce. Stalo by se například složitým postupem, jak vykreslit předchozí text kurzívou vždy, když uživatel umístí kurzor na DIVa kurzívu vypne, když kurzor opustí DIV. Čas by se stal problémem, pokud byste tímto způsobem potřebovali manipulovat s velkým počtem stylů.

Následující postup obsahuje kód, který můžete použít k snadné manipulaci se styly u dokumentů a prvků HTML. Tento postup vyžaduje, abyste věděli, jak provádět základní úkoly v modelu Windows Forms, jako je například vytvoření nového projektu a přidání ovládacího prvku do formuláře.

Zpracování změn stylu v aplikaci Windows Forms

  1. Vytvořte nový projekt Windows Forms.

  2. Vytvořte nový soubor třídy, který končí příponou odpovídající vašemu programovacímu jazyku.

  3. Zkopírujte kód třídy StyleGenerator v části Příklad tohoto tématu do souboru třídy a uložte kód.

  4. Uložte následující kód HTML do souboru s názvem Test.htm.

    <HTML>
        <BODY>
    
            <DIV style="font-face:arial;font-weight:bold;">
                Hello, world!
            </DIV><P>
    
            <DIV>
                Hello again, world!
            </DIV><P>
    
        </BODY>
    </HTML>
    
  5. Přidejte ovládací prvek WebBrowser s názvem webBrowser1 do hlavního formuláře projektu.

  6. Do souboru kódu projektu přidejte následující kód.

    Důležitý

    Ujistěte se, že obslužná rutina události webBrowser1_DocumentCompleted je nakonfigurovaná jako naslouchací proces pro událost DocumentCompleted. V sadě Visual Studio poklikejte na ovládací prvek WebBrowser; v textovém editoru nakonfigurujte naslouchací proces programově.

    StyleGenerator sg = null;
    HtmlElement elem = null;
    
    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        sg = new StyleGenerator();
    
        webBrowser1.Document.MouseOver += new HtmlElementEventHandler(Document_MouseOver);
        webBrowser1.Document.MouseLeave += new HtmlElementEventHandler(Document_MouseLeave);
    }
    
    void Document_MouseOver(object sender, HtmlElementEventArgs e)
    {
        elem = webBrowser1.Document.GetElementFromPoint(e.MousePosition);
        if (elem.TagName.Equals("DIV"))
        {
            sg.ParseStyleString(elem.Style);
            sg.SetStyle("font-style", "italic");
            elem.Style = sg.GetStyleString();
        }
    }
    
    void Document_MouseLeave(object sender, HtmlElementEventArgs e)
    {
        if (elem != null)
        {
            sg.RemoveStyle("font-style");
            elem.Style = sg.GetStyleString();
            // Reset, since we may mouse over a new DIV element next time.
            sg.Clear();
        }
    }
    
    Public Class Form1
    
        Dim SG As StyleGenerator = Nothing
        Dim Elem As HtmlElement = Nothing
        Dim WithEvents DocumentEvents As HtmlDocument
    
        Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
            SG = New StyleGenerator()
            DocumentEvents = WebBrowser1.Document
        End Sub
    
        Private Sub Document_MouseOver(ByVal sender As Object, ByVal e As HtmlElementEventArgs) Handles DocumentEvents.MouseOver
            Elem = WebBrowser1.Document.GetElementFromPoint(e.MousePosition)
            If Elem.TagName.Equals("DIV") Then
                SG.ParseStyleString(Elem.Style)
                SG.SetStyle("font-style", "italic")
                Elem.Style = SG.GetStyleString()
            End If
        End Sub
    
        Private Sub Document_MouseLeave(ByVal sender As Object, ByVal e As HtmlElementEventArgs) Handles DocumentEvents.MouseLeave
            If (Elem IsNot Nothing) Then
                SG.RemoveStyle("font-style")
                Elem.Style = SG.GetStyleString()
                ' Reset, since we may mouse over a new DIV element next time.
                SG.Clear()
            End If
        End Sub
    End Class
    
  7. Spusťte projekt. Spusťte kurzor na první DIV, abyste mohli sledovat účinky kódu.

Příklad

Následující příklad kódu ukazuje úplný kód pro třídu StyleGenerator, která parsuje existující hodnotu stylu, podporuje přidávání, změny a odebírání stylů a vrací novou hodnotu stylu s požadovanými změnami.

using System;
using System.Collections.Generic;
using System.Text;

namespace ManagedDOMStyles
{
    public class StyleGenerator
    {
        private Dictionary<string, string> styleDB;

        public StyleGenerator()
        {
            styleDB = new Dictionary<string, string>();
        }

        public bool ContainsStyle(string name)
        {
            return(styleDB.ContainsKey(name));
        }

        public string SetStyle(string name, string value)
        {
            string oldValue = "";

            if (!(name.Length > 0))
            {
                throw (new ArgumentException("Parameter name cannot be zero-length."));
            }
            if (!(value.Length > 0))
            {
                throw (new ArgumentException("Parameter value cannot be zero-length."));
            }

            if (styleDB.ContainsKey(name))
            {
                oldValue = styleDB[name];
            }

            styleDB[name] = value;

            return (oldValue);
        }

        public string GetStyle(string name)
        {
            if (!(name.Length > 0))
            {
                throw (new ArgumentException("Parameter name cannot be zero-length."));
            }

            if (styleDB.ContainsKey(name))
            {
                return (styleDB[name]);
            }
            else
            {
                return ("");
            }
        }

        public void RemoveStyle(string name)
        {
            if (styleDB.ContainsKey(name))
            {
                styleDB.Remove(name);
            }
        }

        public string GetStyleString()
        {
            if (styleDB.Count > 0)
            {
                StringBuilder styleString = new StringBuilder("");
                foreach (string key in styleDB.Keys)
                {
                    styleString.Append(String.Format("{0}:{1};", (object)key, (object)styleDB[key]));
                }

                return (styleString.ToString());
            }
            else
            {
                return ("");
            }
        }

        public void ParseStyleString(string styles)
        {
            if (styles.Length > 0)
            {
                string[] stylePairs = styles.Split(new char[] { ';' });
                foreach(string stylePair in stylePairs)
                {
                    if (stylePairs.Length > 0)
                    {
                        string[] styleNameValue = stylePair.Split(new char[] { ':' });
                        if (styleNameValue.Length == 2)
                        {
                            styleDB[styleNameValue[0]] = styleNameValue[1];
                        }
                    }
                }
            }
        }

        public void Clear()
        {
            styleDB.Clear();
        }
    }
}
Imports System.Collections.Generic
Imports System.Text

Public Class StyleGenerator
    Dim styleDB As Dictionary(Of String, String)

    Public Sub New()
        styleDB = New Dictionary(Of String, String)()
    End Sub


    Public Function ContainsStyle(ByVal name As String) As Boolean
        Return styleDB.ContainsKey(name)
    End Function


    Public Function SetStyle(ByVal name As String, ByVal value As String) As String
        Dim oldValue As String = ""

        If (Not name.Length > 0) Then
            Throw New ArgumentException("Parameter name cannot be zero-length.")
        End If
        If (Not value.Length > 0) Then
            Throw New ArgumentException("Parameter value cannot be zero-length.")
        End If

        If (styleDB.ContainsKey(name)) Then
            oldValue = styleDB(name)
        End If

        styleDB(name) = value

        Return oldValue
    End Function

    Public Function GetStyle(ByVal name As String) As String
        If (Not name.Length > 0) Then
            Throw New ArgumentException("Parameter name cannot be zero-length.")
        End If

        If (styleDB.ContainsKey(name)) Then
            Return styleDB(name)
        Else
            Return ""
        End If
    End Function

    Public Sub RemoveStyle(ByVal name As String)
        If (styleDB.ContainsKey(name)) Then
            styleDB.Remove(name)
        End If
    End Sub

    Public Function GetStyleString() As String
        If (styleDB.Count > 0) Then
            Dim styleString As New StringBuilder("")
            Dim key As String
            For Each key In styleDB.Keys
                styleString.Append(String.Format("{0}:{1};", CType(key, Object), CType(styleDB(key), Object)))
            Next key

            Return styleString.ToString()
        Else
            Return ""
        End If
    End Function

    Public Sub ParseStyleString(ByVal styles As String)
        If (styles.Length) > 0 Then
            Dim stylePairs As String() = styles.Split(New Char() {";"c})
            Dim stylePair As String
            For Each stylePair In stylePairs
                If (stylePairs.Length > 0) Then
                    Dim styleNameValue As String() = stylePair.Split(New Char() {":"c})
                    If (styleNameValue.Length = 2) Then
                        styleDB(styleNameValue(0)) = styleNameValue(1)
                    End If
                End If
            Next stylePair
        End If
    End Sub


    Public Sub Clear()
        styleDB.Clear()
    End Sub
End Class

Viz také