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

JavaScript로 text-align: justify 상태에서 블록의 마지막 줄 정렬을 설정하는 방법

JavaScript에서 textAlignLast 속성을 사용하면, text-alignjustify(양쪽 정렬)로 설정된 상태에서 블록의 마지막 줄 또는 강제 줄 바꿈 바로 앞의 줄이 어떻게 정렬될지 지정할 수 있습니다.

textAlignLast 속성이란?

양쪽 정렬(justify)된 텍스트에서는 기본적으로 마지막 줄이 왼쪽에 맞춰집니다. 하지만 textAlignLast 속성을 활용하면 이 마지막 줄의 정렬 방식을 자유롭게 변경할 수 있습니다. 예를 들어 이 속성을 right로 설정하면 마지막 줄이 오른쪽으로 정렬됩니다.

예제 코드

아래 코드를 실행해 보면, 버튼을 클릭했을 때 JavaScript를 통해 마지막 줄의 정렬이 오른쪽으로 변경되는 것을 확인할 수 있습니다.

<!DOCTYPE html>
<html>
   <head>
      <style>
         #myDIV {
            text-align: justify;
         }
      </style>
   </head>

   <body>
      <div id = "myText">
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
      </div>
      <button onclick = "display()"> Set Alignment </button>
      <script>
         function display() {
            document.getElementById("myText").style.textAlignLast = "right";
         }
      </script>
   </body>
</html>

동작 원리 설명

위 예제에서는 다음과 같은 순서로 동작합니다.

1. CSS에서 #myDIV 요소에 text-align: justify;를 적용하여 텍스트가 양쪽 정렬되도록 합니다.
2. 버튼을 클릭하면 display() 함수가 호출됩니다.
3. 함수 내부에서 style.textAlignLast 속성을 "right"로 설정하여 마지막 줄이 오른쪽으로 정렬됩니다.

참고 사항

textAlignLast 속성에는 right 외에도 left, center, justify, start, end 등 다양한 값을 사용할 수 있으므로, 디자인 의도에 맞게 마지막 줄의 정렬 방식을 유연하게 조절할 수 있습니다.