[jQuery] 페이지 로드 후 특정 div 이동하기

2021. 8. 9. 17:51Web/jQuery

728x90

jQuery를 이용해서 웹페이지가 로드 됐을 때 특정 div 로 이동하는 방법을 알아보겠습니다.

 

아래 소스는 <div>태그 안에 <img>태그를 넣어

red, orange, yellow 색에 해당하는 jpg 이미지 파일을 지정했습니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>javascript focus</title>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    </head>
    <body>
        <div id="red">
            <img src="img/red.jpg">
        </div>
        <div id="orange">
            <img src="img/orange.jpg">
        </div>
        <div id="yellow">
            <img src="img/yellow.jpg">
    </body>
</html>
cs


웹브라우저로 열어보면 아래와 같은 구조를 갖고 있고
이 경우는 마우스로 스크롤을 내렸습니다.

 

이 상태에서 <script> 태그를 추가하겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>javascript focus</title>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    </head>
    <body>
        <div id="red">
            <img src="img/red.jpg">
        </div>
        <div id="orange">
            <img src="img/orange.jpg">
        </div>
        <div id="yellow">
            <img src="img/yellow.jpg">
    </body>
 
    <script type="text/javascript" charset="utf-8">     
        $(document).ready(function () {
            $('html, body').animate({
                scrollTop: $('#orange').offset().top
        }, 'fast'); //페이지 로드 시 해당 id값으로 포커싱 ( fast or slow  )
    });
    </script>
</html>
cs

animate를 이용해 로드 시 id값이 orange인 곳에 스크롤 되도록 지정했습니다.

 

결과값을 확인하기 위해 웹브라우저를 실행하면 바로 orange로 이동하는 걸 볼 수 있습니다.

 

'Web > jQuery' 카테고리의 다른 글

[jQuery] textarea 글자 수 제한  (0) 2021.08.13