【发布时间】:2017-08-15 19:30:59
【问题描述】:
我正在尝试创建一个脚本,当用户垂直滚动时将 div 从右向左移动。它应该对任何具有“sidepara”类的 div 产生这种效果。如果 div 可见(用户已经滚动到它),它应该只移动它。我无法正确计算数学...。将 div 水平移动到与垂直滚动位置成比例的正确公式是什么?
$(function() {
$(window).scroll(function() {
console.clear();
$(".sidepara").each(function() {
var sY = $(this).position().top - $(window).scrollTop(),
dY = $(this).position().top,
wH = window.innerHeight;
var scrollPercent = (sY / (dY - wH));
var position = (scrollPercent * ($(document).width()));
position = window.innerWidth - position;
$(this).css("margin-left", position);
console.log("scoll Y: " + sY);
console.log("div Y: " + dY);
console.log("div X: " + position);
console.log("window height: " + wH);
console.log("scrollPercent: " + scrollPercent);
console.log("----");
//print number for debugging
$(this).html(position);
});
})
});
html,
body {
margin: 0;
padding: 0;
}
.stretch {
height: 2000px;
}
.sidepara {
color: red;
}
.parallaxContainer {
overflow: hidden;
width: 100%;
height: 256px;
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stretch"></div>
<div class="parallaxContainer">
<!-- <img src="helloworld.png" class="sidepara" /> -->
<div class="sidepara"></div>
</div>
<div class="stretch"></div>
<div class="parallaxContainer">
<!-- <img src="helloworld.png" class="sidepara" /> -->
<div class="sidepara"></div>
</div>
<div class="stretch"></div>
<div class="parallaxContainer">
<!-- <img src="helloworld.png" class="sidepara" /> -->
<div class="sidepara"></div>
</div>
<div class="stretch"></div>
【问题讨论】:
-
我建议您在 div 在视口内时应用您的数学。要判断 div 是否在视口中,您可以咨询this answer
-
有趣!我去看看!
标签: javascript jquery html