다음을 통해 공유


방법: 관리되는 HTML 문서 개체 모델의 요소에 대한 스타일 변경

HTML에서 스타일을 사용하여 문서 및 해당 요소의 모양을 제어할 수 있습니다. HtmlDocumentHtmlElement는 다음 형식의 스타일 문자열을 사용하는 Style 속성을 지원합니다.

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

다음은 글꼴을 Arial로 설정하고 모든 텍스트를 굵게 설정하는 스타일 문자열이 있는 DIV입니다.

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

Style 속성을 사용하여 스타일을 조작할 때 발생하는 문제는 문자열에서 개별 스타일 설정을 추가하고 제거하는 것이 번거로울 수 있다는 것입니다. 예를 들어 사용자가 커서를 DIV 위에 놓을 때마다 기울임꼴로 이전 텍스트를 렌더링하고 커서가 DIV에서 벗어나면 기울임꼴을 해제하는 복잡한 프로시저가 됩니다. 이러한 방식으로 많은 수의 스타일을 조작해야 하는 경우 시간이 많이 걸릴 수 있습니다.

다음 프로시저에는 HTML 문서 및 요소의 스타일을 쉽게 조작하는 데 사용할 수 있는 코드가 포함되어 있습니다. 이 프로시저를 수행하려면 새 프로젝트를 만들고 양식에 컨트롤을 추가하는 등 Windows Forms의 기본 작업을 수행하는 방법을 알고 있어야 합니다.

Windows Forms 애플리케이션에서 스타일 변경 내용을 처리하려면

  1. 새 Windows Forms 프로젝트를 만듭니다.

  2. 프로그래밍 언어에 적합한 확장명으로 끝나는 새 클래스 파일을 만듭니다.

  3. 이 토픽의 예제 섹션에 있는 StyleGenerator 클래스 코드를 클래스 파일에 복사하고 코드를 저장합니다.

  4. 다음 HTML을 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. 프로젝트의 기본 양식에 webBrowser1이라는 이름의 WebBrowser 컨트롤을 추가합니다.

  6. 프로젝트의 코드 파일에 다음 코드를 추가합니다.

    중요합니다

    webBrowser1_DocumentCompleted 이벤트 처리기가 DocumentCompleted 이벤트에 대한 수신기로 구성되어 있는지 확인합니다. Visual Studio에서 WebBrowser 컨트롤을 두 번 클릭하고 텍스트 편집기에서 프로그래밍 방식으로 수신기를 구성합니다.

    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. 프로젝트를 실행합니다. 첫 번째 DIV에 커서를 실행하여 코드의 효과를 관찰합니다.

예시

다음 코드 예제에서는 기존 스타일 값을 구문 분석하고 스타일 추가, 변경 및 제거를 지원하고, 요청된 변경 내용이 포함된 새 스타일 값을 반환하는 클래스의 전체 코드를 StyleGenerator 보여 줍니다.

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

참고하십시오