스크롤 하다가 원하는 요소가 화면에 보일 때 transform
2023. 11. 24. 19:19ㆍjs
스크롤 하다가 원하는 요소가 화면에 출력되면 trnasform해서 x좌표 이동
드래그로도 transform x 이동 가능
html
<div class="image-container for_mo" id="imageContainer">
<div class="img_box"><img src="/img/left.png" alt="이미지 1" id="image1"></div>
<div class="img_box"><img src="/img/right.png" alt="이미지 2" id="image2"></div>
</div>
css
.image-container{
display: flex;
flex-direction: row; /* 이미지를 가로로 배치 */
width: 150%; /* 이미지 컨테이너의 가로 크기를 이미지 두 개의 너비로 설정 */
transition: transform 0.5s ease-in-out;
}
.land_ti_wrap .left_box .image-container .img_box {
flex: 1; /* 각 이미지 박스가 동일한 너비를 가지도록 설정 */
padding: 0;
margin-top: 0;
}
script
<script>
let isMouseDown = false;
let startX = 0;
let translateX = 0;
let isImage1Visible = true;
let startPoint = 0;
let endPoint = 0;
let isScrolling = false;
// 스크롤 이벤트 리스너 추가
function handleScroll() {
const imageContainer = document.getElementById('imageContainer');
let { top, bottom } = imageContainer.getBoundingClientRect();
const threshold = window.innerHeight * 0.3;
if (top < threshold && bottom > 0) {
imageContainer.style.transform = `translateX(-40%)`;
} else {
imageContainer.style.transform = `translateX(0)`;
}
}
// 스크롤 이벤트에 대한 핸들러 등록
window.addEventListener('scroll', handleScroll);
// 초기에 한 번 실행해서 초기 상태를 설정
handleScroll();
// 이미지 요소에 mousedown 이벤트 추가
imageContainer.addEventListener("touchstart", (e) => {
console.log("touchstart", e.touches[0].pageX);
startPoint = e.touches[0].pageX; // 터치가 시작되는 위치 저장
});
imageContainer.addEventListener("touchend", (e) => {
console.log("touchend", e.changedTouches[0].pageX);
endPoint = e.changedTouches[0].pageX; // 터치가 끝나는 위치 저장
if (startPoint < endPoint) {
// 오른쪽으로 스와이프 된 경우
imageContainer.style.transform = `translateX(0)`;
} else if (startPoint > endPoint) {
// 왼쪽으로 스와이프 된 경우
imageContainer.style.transform = `translateX(-50%)`;
}
});
</script>
'js' 카테고리의 다른 글
실시간 검색어 / 세로 텍스트 롤링 배너 1개씩 (0) | 2024.01.25 |
---|---|
특정 div 지날 때 div에 on 클래스 추가 삭제 (0) | 2024.01.23 |
스크롤 시 특정 컨텐츠 아래에서 위로 올라오는 효과(+fade in) (0) | 2023.11.23 |
marguee.js 흐르는 느낌의 슬라이드 (가로, 세로) (0) | 2023.11.23 |
[js] js style display (0) | 2022.06.07 |