본문 바로가기

HTML/Javascript 기초

[Javascript] offsetParent 사용하기

css의 position 사용법

(1) static
 - 모든 태그가 처음에 static 으로 설정됨(기본값)
 - 태그의 위치는 소스에 표시된 순서에 따라서 왼쪽에서 오른쪽, 위에서 아래로 쌓인다.

(2) relative
 - static 모드에서 표시된 위치에서 자리를 변경하고자 할 때 사용
 - 사용하는 옵션
  > top, right, bottom, left 속성을 사용해서 위치 조절

(3) absolute
 - static 속성을 가지고 있지 않은 부모를 기준으로 위치를 설정
 - position 속성이 relative, static, fixed인 태그가 없으면 가장 위의 body를 기준으로 위치 설정

(4)
 - 스크롤이 되더라도 그 자리에 고정되는 position


offsetParent를 이용하여 부모 좌표를 구할 수 있다.

여기서 부모좌표는 static이 아닌 postion으로 선언된 노드를 이야기한다.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../../js/jquery-3.5.1.min.js"></script>
    <style>
        #parent1 {
            position: absolute;
            width: 300px;
            height: 300px;
            top: 100px;
            background-color: #ccc;
        }

        #parent2 {
            margin: 50px;
            background-color: #ff0;
            width: 200px;
            height: 200px;
        }

        #child {
            position: absolute;
            background-color: #f00;
            width: 100px;
            height: 100px;
            left: 50px;
            top: 100px;
        }
    </style>
    <script>
        $(document).ready(function () {
            var $parent = $("#child").offsetParent(); // 부모 좌표 구하기
            console.log("id = " + $parent.attr("id"));
        });
    </script>
</head>

<body>
    <div id="parent1">
        <div id="parent2">
            <div id="child">
            </div>
        </div>
    </div>
</body>

</html>

 

그러면 가장 바깥에 있는 노드가 console에 표시된걸 볼 수 있다.

728x90
반응형