반응형
<!DOCTYPE html>
<html>
<head>
<title>자동 섹션 슬라이드</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
section {
height: 500px;
padding: 20px;
display: none; /* 모든 섹션을 숨깁니다. */
}
#section1 {
background-color: #f0f0f0;
}
#section2 {
background-color: #e0e0e0;
}
</style>
</head>
<body>
<section id="section1">
<h1>섹션 1</h1>
<p>이곳은 섹션 1의 내용입니다.</p>
</section>
<section id="section2">
<h1>섹션 2</h1>
<p>이곳은 섹션 2의 내용입니다.</p>
</section>
<script>
document.addEventListener("DOMContentLoaded", function() {
const sections = document.querySelectorAll("section");
let currentSectionIndex = 0;
function showSection(index) {
// 현재 섹션 숨기기
sections[currentSectionIndex].style.display = "none";
// 새로운 섹션 보이기
sections[index].style.display = "block";
// 현재 섹션 인덱스 업데이트
currentSectionIndex = index;
}
function slideNext() {
const nextSectionIndex = (currentSectionIndex + 1) % sections.length;
showSection(nextSectionIndex);
}
// 첫 번째 섹션 표시
showSection(0);
// 3초마다 다음 섹션으로 이동
setInterval(slideNext, 3000);
});
</script>
</body>
</html>
자동으로 섹션을 슬라이드 하는 기능을 구현한 예시이다.
HTML/CSS 설명은 제외하고
JavaScript 설명만 추가하면
document.querySelectorAll("section") 은 페이지 내의 모든 섹션 요소를 선택한다.
currentSectionIndex 는 현재 표시되고 섹션을 보이도록 변경하는 함수이다.
slideNext() 다음 섹션으로 슬라이드 하는 함수이다.
setInterval(slideNext, 3000) 3초마다 slideNext() 함수를 호출하여 다음 섹션을 자동으로 슬라이드 한다.
반응형
'JavaScript' 카테고리의 다른 글
[JavaScript] 화면 크기에 따라 변하는 반응형 레이아웃 (0) | 2023.07.27 |
---|---|
[JavaScript] 선택해서 섹션 이동하기 (0) | 2023.07.27 |
[JavaScript] ES6 문법 개념 (0) | 2023.07.26 |
[JavaScript] 버블링(Bubbling) (0) | 2023.07.26 |
[JavaScript] HTML/CSS/JS 간단한 팝업창 만들기 (0) | 2023.07.26 |