Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 텍스트 장식(text-decoration) 색상을 설정하는 방법

텍스트 장식(text-decoration)의 색상을 설정하려면 JavaScript에서 textDecorationColor 속성을 사용하면 됩니다. 이 속성은 밑줄(underline), 윗줄(overline), 취소선(line-through)과 같은 텍스트 장식에 적용되는 선의 색상을 지정합니다.

기본 사용법

먼저 style.textDecoration으로 장식 종류를 지정한 뒤, style.textDecorationColor를 사용해 원하는 색상을 설정합니다. 색상 값은 'red', '#ff0000', 'rgb(255,0,0)' 등 CSS에서 허용하는 형식을 그대로 사용할 수 있습니다.

예제

아래 코드를 실행하고 버튼을 클릭하면 텍스트에 빨간색 밑줄이 적용됩니다.

<!DOCTYPE html>
<html>
   <body>
      <div id = "myText"> This is demo text. </div> <br>
      <button onclick = "display()"> Set Text Decoration </button>
      <script>
         function display() {
            document.getElementById("myText").style.textDecoration = "underline";
            document.getElementById("myText").style.textDecorationColor = "red";
         }
      </script>
   </body>
</html>

코드 설명

버튼을 클릭하면 display() 함수가 실행되어 id가 'myText'인 요소에 밑줄을 추가하고, 해당 밑줄의 색상을 빨간색(red)으로 변경합니다. 이처럼 textDecorationColor는 반드시 textDecoration 또는 textDecorationLine과 함께 사용해야 실제 화면에 색상이 표시됩니다.