HTML onscroll 이벤트 속성은 웹 문서에서 특정 요소의 스크롤바를 이용해 내용을 스크롤할 때 지정된 자바스크립트 코드를 실행하는 이벤트 핸들러입니다. 스크롤 위치에 따라 콘텐츠를 동적으로 변경하거나, 무한 스크롤 구현, 고정 헤더 효과 등 다양한 UI 인터랙션에 폭넓게 활용됩니다.
문법(Syntax)
onscroll 이벤트 속성의 기본 문법은 다음과 같습니다 −
<tagname onscroll="script"></tagname>
이제 onscroll 이벤트 속성의 실제 동작 예제를 살펴보겠습니다 −
예제(Example)
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: #000;
height: 100vh;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
text-align: center;
padding: 20px;
}
.box-para {
border: 2px solid #fff;
padding: 10px;
width: 200px;
height: 200px;
overflow: scroll;
margin: 1rem auto;
}
</style>
</head>
<body>
<h1>HTML onscroll Event Attribute Demo</h1>
<p onscroll="scrollFn()" class="box-para">
This is a paragraph element with some dummy text. This is a paragraph element with some dummy text.
This is a paragraph element with some dummy text. This is a paragraph element with some dummy text.
This is a paragraph element with some dummy text. This is a paragraph element with some dummy text.
This is a paragraph element with some dummy text. This is a paragraph element with some dummy text.
This is a paragraph element with some dummy text. This is a paragraph element with some dummy text.
This is a paragraph element with some dummy text. This is a paragraph element with some dummy text.
This is a paragraph element with some dummy text. This is a paragraph element with some dummy text.
This is a paragraph element with some dummy text.</p>
<p>위 단락의 텍스트를 스크롤하면 글자 크기가 커집니다</p>
<script>
function scrollFn() {
document.querySelector(".box-para").style.fontSize = "1.5rem";
}
</script>
</body>
</html>실행 결과(Output)

위 예제에서는 overflow: scroll 속성으로 생성된 박스 안의 단락 텍스트를 스크롤하면, onscroll 이벤트가 발생하여 scrollFn() 함수가 호출됩니다. 이 함수는 해당 단락의 글자 크기를 1.5rem으로 변경하는 역할을 합니다. 직접 스크롤해 보면서 onscroll 이벤트 속성의 동작 방식을 확인해 보세요 −
