我正在尝试创建一些很酷的视差效果,如果我可以制作一个带有bg图像的div,它具有属性background-attachement: fixed
滚动一点(比正常滚动慢)而不是让它静止不动?
这就是我的css的样子:
.parallax{
height: 400px !important;
width: 100%;
background-size: cover;
background-attachment: fixed;
}
这是我的div
<div class="parallax" style="background-image: url('img/image.jpg'); ">
</div>
我试过这个:
$('div.parallax').each(function(){
$scroll_speed = 10;
$this = $(this);
$(window).scroll(function() {
$bgScroll = -(($win.scrollTop() - $this.offset().top)/ $scroll_speed);
$bgPosition = 'center '+ $bgScroll + 'px';
$this.css({ backgroundPosition: $bgPosition });
});
});
似乎工作,只是我不能增加scroll_speed,即使我更改变量,任何人都可以帮助我吗?
答案 0 :(得分:0)
通过更改因子可以轻松调整滚动速度。因子5将更快滚动速度,而20将更慢滚动速度。
$('div.parallax').each(function() {
$scroll_speed = 5;
$this = $(this);
$('#container').scroll(function() {
$bgScroll = -(($('#container').scrollTop() - $this.offset().top) / $scroll_speed);
$bgPosition = 'center ' + $bgScroll + 'px';
$this.css({
backgroundPosition: $bgPosition
});
});
});
.parallax {
height: 400px !important;
width: 100%;
background-size: cover;
background-attachment: fixed;
background-position: center 0;
font-weight: bold;
font-size: 20px;
color: red;
}
#container {
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="parallax" style="background-image: url('http://imgs.xkcd.com/comics/jack_and_jill.png'); ">
bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>bla bla bla
<br>
</div>
</div>