투케이2K

532. (javaScript) [간단 소스] 자바스크립트 MutationObserver 사용해 실시간 특정 객체 css style 스타일 변경 감지 수행 본문

JavaScript

532. (javaScript) [간단 소스] 자바스크립트 MutationObserver 사용해 실시간 특정 객체 css style 스타일 변경 감지 수행

투케이2K 2026. 5. 19. 19:29
728x90
반응형

[개발 환경 설정]

개발 툴 : Edit++ / Vscode

개발 언어 : JavaScript

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web


- 개발 기술 : 자바스크립트 / JavaScript / MutationObserver


- 사전) 👉 MutationObserver 를 사용할 수 있는 버전 간략 설명 :  

  >> Chrome : ✅ 26+

  >> Edge (Chromium) : ✅ 12+
  
  >> Firefox : ✅ 14+
  
  >> Safari : ✅ 6.1+
  
  >> Opera : ✅ 15+
  
  >> IE : ✅ 11

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------

<!DOCTYPE HTML>
<html lang="ko" translate="no">
<head>
    <title>javaScriptTest</title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- 반응형 구조 만들기 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

    <!-- Chrome / Edge (Chromium)에서 자동 번역 기능을 완전히 비활성화 -->
    <meta name="google" content="notranslate">

    <!-- 내부 CSS 스타일 지정 -->
    <style>

      html, body {
        width: 100%;
        height: 100%;
        margin : 0 auto;
        padding : 0;
        border : none;
        background-color: #666;
      } 

    </style>





    <!-- [CDN 주소 설정] --> 
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>






    <!-- [자바스크립트 코드 지정] -->
    <script type="module">      

      // -----------------------------------------------------------------
      // ✅ [Window.onload 웹 브라우저 로드 완료]
      // -----------------------------------------------------------------
      window.onload = async function() {
        console.log("[window onload] : [html 최초 로드 및 이벤트 상시 대기 실시] : [start]");

        try {

          // ------------------------------------------------------
          // ✅ [MutationObserver 기본 설명 정리]
          // ------------------------------------------------------
          /*
          1. MutationObserver 는 👉 DOM의 구조/속성/텍스트 변경을 감지하는 API 입니다.
          ---------------------------------------------------------
          2. MutationObserver 는 특정 요소에 변화가 생기면 callback 이 실행됩니다.
          ---------------------------------------------------------
          3. MutationObserver 기본 동작 구조 : 
                    
          const observer = new MutationObserver(callback);
          observer.observe(target, options);
          ---------------------------------------------------------
          4. 동작 로그 출력 예시 

            MutationObserver : 지원됨
            initColor :  rgb(138, 43, 226)
            속성 변경 :  style  :  rgb(255, 0, 0)
            속성 변경 :  style  :  rgb(0, 0, 255)
          ---------------------------------------------------------
          // */    
          
          
          // [MutationObserver 지원 여부 체크]
          if ('MutationObserver' in window) {
            console.log('MutationObserver : 지원됨');

            // [MutationObserver 사용해 특정 객체 css style 변경 이벤트 감지]
            const target = document.getElementById('box');
            
            const observer = new MutationObserver(mutations => {
              mutations.forEach(mutation => {
                //console.log('MutationObserver : mutations : ', mutation);

                if (mutation.type === 'attributes') {

                  /*                
                  mutation.type           // 변경 종류
                  mutation.target         // 변경된 요소
                  mutation.attributeName  // 변경된 속성
                  */

                  console.log('속성 변경 : ', mutation.attributeName, ' : ', getComputedStyle(target).backgroundColor);

                }
              });
            });


            // [observer 에 특정 객체 매핑 수행]          
            observer.observe(target, {
              attributes: true,
              attributeFilter: ['class', 'style']
            });
            
            // observer.disconnect(); // 감지 해제


            // [현재 해당 객체 배경 색상 확인]
            let initColor = getComputedStyle(target).backgroundColor;
            console.log('initColor : ', initColor);


            // [타이머 등록 후 일정 시간 후 배경 색상 변경]
            setTimeout(() => {
              target.style.backgroundColor = 'red';
            }, 2000);


            // [타이머 등록 후 일정 시간 후 배경 색상 변경]
            setTimeout(() => {
              target.style.backgroundColor = 'blue';
            }, 4000);


          } else {
            console.error('MutationObserver : 지원 안됨');
          }


        }
        catch (exception) {
          console.error("[window onload] : [Exception] : ❌ 예외 상황 발생 : ", exception);

        }

      };
      

    </script>


</head>


<body>

  <!-- 특정 div 객체 생성 -->
  <div id="box" style="width: 20%; height: 20%; background-color: blueviolet;"></div>

</body>

</html>

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------

▶️ [document 사용해 브라우저 사이즈 확인, 스타일 (style) 속성 값 확인 및 변경, 텍스트 (text) 값 확인 및 변경]

https://kkh0977.tistory.com/831

https://blog.naver.com/kkh0977/222389422173?trackingCode=blog_bloghome_searchlist


▶️ [Jquery 사용해 브라우저 사이즈 확인, 스타일 (style) 속성 값 확인 및 변경, 텍스트 (text) 값 확인 및 변경]

https://kkh0977.tistory.com/832

https://blog.naver.com/kkh0977/222389479461?trackingCode=blog_bloghome_searchlist


▶️ [자바스크립트 사용해 p 태그 텍스트 확인 및 변경 , css style 속성 변경 실시]

https://kkh0977.tistory.com/787

https://blog.naver.com/kkh0977/222378535016?trackingCode=blog_bloghome_searchlist

-----------------------------------------------------------------------------------------
 
728x90
반응형
Comments