相对于窗口而不是其父级的视差内容偏移

时间:2016-12-22 09:25:21

标签: html css parallax

我正在练习视差效果,我想在我的页面中应用它(如果掌握了)。在每个#wrap内,我希望当页面向上和向下滚动时.bar不可移动,因此我将position设置为fixed并更改了z-index为0使下面的内容看起来像滑动。问题是,虽然.bar#wrap,但position是粘在一起的,它们的偏移是相对于窗口的,而不是它们的relative,所以结果是.bar被固定在窗口中间,而不是在父母的内部。有人可以帮我解决这个问题吗?

HTML

<div class="wrap-1">
    <div class="bar-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua.</div>
</div>

<div style="height: 1000px;"></div> <!-- added for scrolling purposes -->

<div class="wrap-2">
    <div class="bar-2">Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
</div>

<div style="height: 1000px;"></div> <!-- added for scrolling purposes -->

CSS

div[class^='wrap'] {
  width: 100%;
  height: 100vh;
  background-image: url("../assets/img/background/fence.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  position: relative;
}
div[class^='wrap'].wrap-1 {
    background-image: url("/link/to/image-background.jpg");
}
div[class^='wrap'].wrap-2 {
    background-image: url("/link/to/image-background.jpg");
}
div[class^='wrap'] div[class^='bar'] {
    width: 100%;
    height: 100px;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 50%;
    transform: translateY(-50%);
}

1 个答案:

答案 0 :(得分:2)

试试这个:

private boolean checkForConvergence(int iteration_number){
    if(counter!=0&&iteration_number!=0){
        return true;
    }
     return false
   }
$(window).scroll(function(){
    $("section div").each(function(){
    $(this).css('margin-top',$(window).scrollTop()-$(this).parent().position().top);
        console.log();
    });
});
{
    height:100%;
}

body,html, .wrapper, section{
    height:100%;
  margin:0;
  padding:0;
}
section{
  margin:0;
    padding:20px;
    overflow:hidden;
}

section div{
    font-size:120px;
}

section div p{
font-size: 20px;
  padding:0;
  margin:0;
}

.wrapper #wrap1 {
background: url(http://p1.pichost.me/i/14/1375274.jpg) no-repeat fixed;
background-position: center center;
background-size:cover;
    color:white;
}
.page-wrapper .wrapper #wrap1 .section-text1 {
position: fixed;
width: 300px;
margin: 0 auto;
padding-top: 100px;
background: #000000;
}
.wrapper #wrap2 {
background: url(http://www.topgear.com/india/images/stories/Car-Bike_topImages/bike.jpg) no-repeat fixed;
background-position: center center;
background-size:cover;
z-index: 3000;
}
.page-wrapper .wrapper #wrap2 .section-text2 {
position: fixed;
width: 300px;
margin: 0 auto;
padding-top: 100px;
background: #000000;
}