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

JavaScript로 요소를 나눌 열(Column) 개수를 설정하거나 반환하는 방법

HTML에서 div 요소를 여러 개의 열로 나누고 싶다면 columnCount 속성을 사용하면 됩니다. 이 속성에 원하는 열 개수를 설정하기만 하면, 브라우저가 해당 요소의 텍스트 콘텐츠를 지정된 열 수만큼 자동으로 분할해 줍니다.

columnCount는 CSS의 column-count 속성에 대응하는 JavaScript 스타일 속성으로, 값을 읽어 현재 설정된 열 개수를 반환할 수도 있고, 새로운 값을 할당해 열 개수를 동적으로 변경할 수도 있습니다.

예제

아래 코드를 실행해 보세요. 버튼을 클릭하면 JavaScript를 통해 div 요소가 4개의 열로 나뉘는 것을 확인할 수 있습니다.

<!DOCTYPE html>
<html>
   <body>
      <p>아래 버튼을 클릭하면 4개의 열이 생성됩니다</p>
      <button onclick="display()">열 나누기</button>
      <div id="myID">
         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.
         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>
      <script>
         function display() {
            document.getElementById("myID").style.columnCount = "4";
         }
      </script>
   </body>
</html>

코드 설명

버튼을 클릭하면 display() 함수가 호출되고, document.getElementById("myID")로 div 요소를 가져온 뒤 style.columnCount에 "4"를 할당합니다. 그 결과 해당 div의 텍스트가 4개의 열에 걸쳐 배치됩니다.

참고 사항

  • columnCount 값으로 "auto"를 설정하면 다른 열 관련 속성(예: columnWidth)에 따라 열 개수가 자동 결정됩니다.
  • 열 사이에 구분선을 추가하려면 columnRule 속성을 함께 사용할 수 있습니다.
  • 이 속성은 Chrome, Firefox, Safari, Edge 등 주요 최신 브라우저에서 모두 지원됩니다.