jQuery / 요소가 순서대로 나타나게 하는 방법
.animate()로 요소를 나타내기
다음과 같이 간단한 예제를 만듭니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <style> body { box-sizing: border-box; margin: 0px; } .jb { height: 200px; padding: 20px; text-align: center; color: #ffffff; } .jb-1 { background-color: #333333; } </style> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script> $( document ).ready( function() { // jQuery Code } ); </script> </head> <body> <div class="jb jb-1">Hello!</div> </body> </html>
opacity의 값을 0으로 정하여 보이지 않게 합니다. 보이지 않을 뿐, 공간은 차지한 상태입니다.
.jb { height: 200px; padding: 20px; text-align: center; color: #ffffff; opacity: 0; }
jQuery의 .animate()를 이용하여 서서히 나타나게 만듭니다.
<script> $( document ).ready( function() { $( '.jb-1' ).animate( { opacity: '1' }, 1000 ); } ); </script>
전체 코드는 다음과 같습니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <style> body { box-sizing: border-box; margin: 0px; } .jb { height: 200px; padding: 20px; text-align: center; color: #ffffff; opacity: 0; } .jb-1 { background-color: #333333; } </style> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script> $( document ).ready( function() { $( '.jb-1' ).animate( { opacity: '1' }, 1000 ); } ); </script> </head> <body> <div class="jb jb-1">Hello!</div> </body> </html>
연달아 나타나게 하기
요소를 몇 개 더 만든 후 차례대로 나타나게 합니다.
- 하나의 요소가 나온 후 그 다음 요소가 나오게 하기 위해서 콜백 함수를 사용합니다.
- 시간 조절을 편하게 하기 위해서 jbTime이라는 변수를 만들었습니다. 그 값을 변경하면 나타나는 속도가 한 번에 바뀝니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <style> body { box-sizing: border-box; margin: 0px; } .jb { height: 200px; padding: 20px; text-align: center; color: #ffffff; opacity: 0; } .jb-1 { background-color: #333333; } .jb-2 { background-color: #444444; } .jb-3 { background-color: #222222; } </style> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script> $( document ).ready( function() { var jbTime = 600; $( '.jb-1' ).animate( { opacity: '1' }, jbTime, function() { $( '.jb-2' ).animate( { opacity: '1' }, jbTime, function() { $( '.jb-3' ).animate( { opacity: '1' }, jbTime ); } ); } ); } ); </script> </head> <body> <div class="jb jb-1">Hello!</div> <div class="jb jb-2">Hello!</div> <div class="jb jb-3">Hello!</div> </body> </html>