视差效果不起作用

时间:2014-01-18 11:50:52

标签: parallax

我正在试图弄清楚我做错了什么,但我没理解。我对这种视差有点新意。我查了一下chrome控制台,找不到任何错误。请你帮助我好吗?

视差效果不起作用它只显示正常的图片,我无法弄清楚问题是什么。可能我做了一些简单的事情,或者忘记了什么。

任何人都有任何想法? :)

<html>
<head>
<style type="text/css">

body{
margin:0;
padding:0;
}
ul{
margin:0;
padding:0;
}
ul li{
list-style:none;
overflow:none;
height:600px;
}
.parallax-background{
height:700px;
}

.parallax1{
background-image:url('parallax1.jpg');

}
.parallax2{
background-image:url('parallax2.jpg');
background-position:50% 100%;

}
.parallax3{
background-image:url('parallax3.jpg');

}
.parallax4{
background-image:url('parallax4.jpg');

}
ul li .subcontent{
position:absolute;
top:500px;
left:100px;
color:white;
font-family:Arial, Helvetica, sans-serif;
}
h1{
font-size:70px;
margin-bottom:0px
}
h2{
font-size:30px;
margin-top:0px;
}

</style>
</head>

<body>

<ul class="parallax">
<li>
<div class="parallax-background parallax1"></div>
</li>
<li>
<div class="parallax-background parallax2"></div>
<div class="subcontent">
<h1> Sample Text</h1>
<h2> Hey there </h2>
</div>
</li>
<li>
<div class="parallax-background parallax3"></div>
</li>
<li>
<div class="parallax-background parallax4"></div>
</li>
</ul>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
(function($) {
var $container = $(".parallax");
var $divs = $container.find("div.parallax-background");
var thingBeingScrolled = document.body;
var liHeight = $divs.eq(0).closest("li").height();
var diffheight = $divs.eq(0).height() - liHeight;
var len = $divs.length;

var i,div,li,offset,scroll ,top, transform, diffHeight;

var offsets = $divs.get().map(function(div,d){
return $(div).offset();
});
var render = function(){
top = thingBeingScrolled.scrollTop;
for(i=0;i<len;i++){

div = $divs[i];
offset = top - offsets[i].top;
scroll = ~~(offset/liHeight * diffHeight);
transform = 'translate3d(0px, ' + scroll + 'px, 0px)';

div.style.MozTransform = transform;
div.style.msTransform = transform;
div.style.Otransform = transform;
div.style.transform = transform;
div.style.webkitTransform = transform;
}
};
(function loop(){
requestAnimationFrame(loop);
render();
})();
})(jQuery);
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

代码难以阅读,可能会将其发布到CodePen.io。

我发现创建视差效果的最简单方法是使用Skrollr.js

这是Simple parallax scrolling tutorial

答案 1 :(得分:0)

我解决了这个问题。

var diffheight = $ divs.eq(0).height() - liHeight;

Spelled diffHeight with a small&#34; h&#34;当我使用它时,我用一个大的&#34; H&#34;

来称呼它

scroll = ~~(offset / liHeight * diffHeight);

所以我简单地将小h变成了一个大的,就是这样。

现在它完美无缺!