[javaScript] 스크롤을 따라 움직이는 레이어 updated_at: 2024-12-14 13:28

스크롤을 따라 움직이는 레이어

js

self.onError=null;
currentX = currentY = 0;
whichIt = null;
lastScrollX = 0; lastScrollY = 0;

var layer = document.getElementById('layer-right');

window.addEventListener('scroll', function() {
  var diffY = window.pageYOffset;
  var diffX = window.pageXOffset;
    // diffX = 0;
  if (diffY != lastScrollY) {
    percent = .2 * (diffY - lastScrollY);
    if (percent > 0) {
      percent = Math.ceil(percent);
    } else {
      percent = Math.floor(percent);
    }
    var top = parseInt(layer.style.top) + percent;
    layer.style.top = top + 'px';
    console.log(layer.style.top)
    lastScrollY = lastScrollY + percent;
  }
  if (diffX != lastScrollX) {
    percent = .2 * (diffX - lastScrollX);
    if (percent > 0) {
      percent = Math.ceil(percent);
    } else {
      percent = Math.floor(percent);
    }
    var left = parseInt(layer.style.left) + percent;
    layer.style.left = left + 'px';
    lastScrollX = lastScrollX + percent;
  }
});


css

#layer-right {
  width:200px; 
  height:200px;
  position:absolute; 
  z-index:1;
  background-color: gray
}

html

<div id='layer-right' style='top: 100px; left: 500px;' > 
내용
 </div>

See the Pen 위아래로 스크롤 컨트롤 by younghyeong ryu (@wangta69) on CodePen.

평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글