Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
27 | 28 | 29 | 30 | 31 |
Tags
- 자동완성방지
- react
- reacts3
- 코드정렬
- prettier
- next #middleware
- s3확장자
- axios
- 자연수 뒤집어 배열로 만들기
- 코딩테스트
- vscode
- EC2
- 리액트코드정렬
- 부족한 금액 계산하기
- AWS
- elasticIP
- Node
- 제일 작은 수 제거하기
- useReducer
- 커밋 한번에
- max_allowed_packet
- utf8mb4
- 리액트
- express
- MySQL
- .env
- dotenv
- interactive_timeout
- 프리티어
- 프로그래머스
Archives
- Today
- Total
Sungtt
3. DOM 스크롤 실시간 감지 본문
오늘은 스크롤을 실시간으로 감지하여 일정 위치에서 애니메이션이 실행되는 코드를 작성하기위해 알아보았다.
스크롤 감지를 위해 쓰이는 내장함수는 아래와 같았다.
이미지 출처 https://developer.mozilla.org/ko/docs/Web/API/Element/getBoundingClientRect
window.pageYoffset
HTML 시작점에서 viewport 시작점까지의 Y축 거리
window.pageXoffset
HTML의 시작점에서 viewport 시작점까지의 X축 거리
element.getBoundingClientRect()
위 이미지에 따라 지정요소와의 거리를 반환해준다.
HTML는 아래와 같다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{
margin: 0;
padding: 0;
list-style-type: none;
}
body {height: 5000px;}
.parent {
background-color: blue;
width: 300px;
height: 300px;
margin: 0 auto;
margin-top: 100px;
position: relative;
}
.child {
position: absolute;
top: 40%;
left: 35%;
background-color: #ccc;
width: 150px;
height: 150px;
}
.value{
position:fixed;
top: 300px;
left: 400px;
font-size: 20px;
}
</style>
<body>
<div class="value"></div>
<div class="parent">
<div id="topChild" class="child">Child
</div>
</div>
</body>
<script src="prac.js"></script>
</html>
자바스크립트는 아래와 같다.
function update(){
const child = document.querySelector(".child");
const value = document.querySelector(".value")
let all = child.getBoundingClientRect();
value.innerHTML = '';
for(let key in all){
if(typeof all[key] !== 'function'){
let para = document.createElement('p');
para.textContent = `${key} : ${all[key]}`;
value.appendChild(para);
}
}
};
document.addEventListener('scroll',update);
update();
출력 결과
'JavaScript' 카테고리의 다른 글
6. 이벤트 핸들러의 방식 (0) | 2022.01.08 |
---|---|
5. data어트리뷰트와 dataset프로퍼티 (0) | 2022.01.07 |
4. html노드 생성과 삭제 (0) | 2022.01.06 |
2. 연산자의 종류 (0) | 2021.12.13 |
1. 변수란 무엇인가? (0) | 2021.12.13 |
Comments