JavaScript로 텍스트 첫 줄 들여쓰기 설정하기
텍스트의 첫 번째 줄 들여쓰기를 설정하려면 JavaScript의 textIndent 속성을 사용합니다. 이 속성은 CSS의 text-indent 스타일과 동일한 역할을 하며, px(픽셀), %, em 등 다양한 단위로 값을 지정할 수 있습니다.
DOM 요소의 style 객체에 접근한 뒤 textIndent 값을 할당하면, 해당 요소 내 문단의 첫 줄이 지정한 크기만큼 들여쓰기됩니다.
예제
다음 코드를 실행하고 버튼을 클릭하면, JavaScript를 통해 텍스트의 첫 번째 줄이 50px만큼 들여쓰기됩니다.
<!DOCTYPE html>
<html>
<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.
</div>
<br>
<button onclick = "display()">Set Text Indent</button>
<script>
function display() {
document.getElementById("myText").style.textIndent = "50px";
}
</script>
</body>
</html>코드 설명
버튼을 클릭하면 display() 함수가 호출되고, document.getElementById()로 id가 "myText"인 div 요소에 접근합니다. 이후 해당 요소의 style.textIndent 속성에 "50px"을 할당하여 첫 줄 들여쓰기가 즉시 적용됩니다.
필요에 따라 값을 "2em", "10%" 등으로 변경하거나, 초기화 시에는 빈 문자열("")을 할당하여 기본값으로 되돌릴 수도 있습니다.