如何根据滚动位置逐步变换元素

时间:2019-04-22 18:22:02

标签: javascript jquery html css

我正在尝试将航路点用于两个特定功能。

  1. 要确定用户是向上滚动还是向下滚动。这正在工作。

  2. 我要弄清楚的第二件事不一定与航路点有关。我试图弄清楚的是如何使代码段中的图像逐步转换:基于滚动进度的translateX。我不确定该怎么做。我在代码段中插入了翻译以显示运动。

基本上,如果您向下滚动,我希望图像根据其所保持的部分/容器向下滚动的程度逐渐向左移动。向上滚动时同样如此,除了图像向右移动。

Check out this site并向下滚动至“ Nike and Snapchat”部分,您将看到Lebron的电话图像。随着您向上或向下滚动,图像会相应移动。这就是我要复制的内容。

有人知道我能做些什么吗?

var homeMainSec = 	$('#homeMainSec');
	
homeMainSec.waypoint(function(direction) {
  if (direction === 'down') {
    $('#homeBoxGridRight img').addClass('slideLeftDisplay');
    console.log('Left Slide');
  }
}, {
  offset: '25%'
});
homeMainSec.waypoint(function(direction) {
  if (direction === 'up') {
    $('#homeBoxGridRight img').addClass('slideRightDisplay');
    console.log('Right Slide');
  }
}, {
  offset: '25%'
});
#homeMainSec {
	width: 100%;
	height: 95vh;
	position: relative;
	margin-top: 70px;
}
.homeMainBlock {
	height: 100%;
	width: 50%;
	display: inline-block;
	vertical-align: top;
	box-sizing: border-box;
}
/*- HomeBoxGridRight Section -*/
#homeBoxGridRight img {
	display: block;
	width: 40%;
	height: auto;
	margin-left: 50%;
}
.slideLeftDisplay {
	transform: translateX(-100px);-webkit-transform: translateX(-100px);
	transition: 1s;-webkit-transition: 1s;
	opacity: 1;
}
.slideRightDisplay {
	transform: translateX(100px);-webkit-transform: translateX(100px);
	transition: 1s;-webkit-transition: 1s;
	opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
<section id="homeMainSec">
  <div class="homeMainBlock" id="homeBoxGridLeft">
  </div><div class="homeMainBlock" id="homeBoxGridRight">
    <img src="https://slidesjs.com/examples/standard/img/example-slide-1.jpg" alt="Image">
  </div>
</section>
<br><br><Br><br><br><br><br><br>

勒布朗的

ge。随着您向上或向下滚动,图像会相应移动。这就是我要复制的内容。

有人知道我能做些什么吗?

1 个答案:

答案 0 :(得分:1)

// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/

let last_known_scroll_position = 0;
let ticking = false;

function doSomething(scroll_pos) {
  // Do something with the scroll position
  document.querySelector('img').style.transform = 'translateX(' + scroll_pos + '%)';
}

window.addEventListener('scroll', function(e) {
  last_known_scroll_position = window.scrollY;

  if (!ticking) {
    window.requestAnimationFrame(function() {
      doSomething(last_known_scroll_position);
      ticking = false;
    });

    ticking = true;
  }
});
相关问题