我正在尝试使用JavaScript获得视差效果。它正常工作但滚动时图像抖动。
的index.html
<!doctype html>
<html>
<head>
<title>ScollingParallex</title>
<link rel="stylesheet" href="css/main.css">
<script type="text/javascript">
window.requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(f){setTimeout(f, 1000/60)}
var ypos,image;
function parallex() {
content = document.getElementById('content');
ypos = window.pageYOffset;
console.log(ypos * .9);
console.log("ypos"+ypos)
content.style.top = ypos * .9+ 'px';
}
// window.addEventListener('scroll', parallex);
window.addEventListener('scroll',function(){
requestAnimationFrame(parallex)
},false)
</script>
</head>
<body>
<div id ="content">
<div class="shape_top_page1">
<div style="width:980px;display:inline-block;background-color:transparent;">
<img src="img/img_mobile_add_photo.png" style="width:330px">
</div>
</div>
</div>
<div id="content">
<div class="shape_top_page2">
<div style="width:980px;display:inline-block;background-color:transparent;">
<img src="img/img_mobile_add_photo1.png" style="width:330px">
</div>
</div>
</disv>
</body>
CSS
body{
margin: 0;
padding: 0;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: 300;
background-color:black;
color: #fff;
}
#image {
position: ;
z-index: -1
}
#content {
height: 750px;
width: 100%;
/*margin-top:-10px; */
background-color:#707070;
position: relative;
z-index: 1;
text-align: center;
}
.center{
text-align: center;
}
.parallax-target{
width:100%;
/*background: #707070;*/
height:700px;
}
.shape_top_page1
{
background : #FAC912;
background : rgba(250, 201, 18, 1);
height: 500px;
text-align: center;
}
.shape_top_page2
{
background : wheat;
/*background : rgba(250, 201, 18, 1);*/
height: 500px;
text-align: center;
}
我已经给了一个容器(内容),里面有一个图像。当我向下滚动时,我能够看到视差效果在行动。但我面临的问题是图像得到一些震动效果(试图当我滚动时,当我故意将鼠标放在滚动条上并单击它并滚动它工作正常时。但是当我在页面上执行自由滚动时,问题就出现了。我没有使用任何jquery插件。
答案 0 :(得分:0)
您有两个ID为“content”的元素,这些元素是无效的HTML,可能会导致抖动。其中一个还有一个等号左边的空格,这也是无效的。通常,浏览器在执行getElementById
时只选择第一个元素,但加上相对定位可能会混淆渲染引擎。它也可能是由你称之为每帧的昂贵getElementById
引起的。最好调用一次并保存参考以供以后使用。这是大多数ppl开始使用jQuery的$(document).ready()
的地方,这样你就可以在元素加载到DOM之后找到它。