我正在试验视差,并试图获得一个不错的缩放滚动,但我正在挣扎的图像变得小于浏览器的宽度和div
的高度。
正如您在我的示例中看到的,当您向下滚动时,包装部分的红色背景是可见的。
您可以在www.adamkhourydesign.com/test上查看示例
HTML格式
<header id="header_container">
<div class="header_back"></div>
<div class="logo"></div>
</header>
CSS
#header_container {
position: relative;
height: 600px;
background-color: rgba(255, 100, 85, 0.5);
background-repeat: no-repeat;
background-size: auto 800px;
background-position: top center;
background-attachment: fixed;
overflow: hidden;
}
.logo {
height: 100px;
width: 100%;
background-image: url(../img/name.png);
background-position: center;
background-repeat: no-repeat;
position: absolute;
top: 50%;
margin-top: -50px;
}
.header_back {
position: relative;
height: 600px;
background-repeat: no-repeat;
background-size: cover;
background-position: top center;
background-attachment: fixed;
background-image: url(../img/header_bg.jpg);
overflow: hidden;
}
jQuery公司
var pContainerHeight = $('#header_container').height();
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
var wZoomIn = 1+(wScroll*.0005);
var wZoomOut = 1-(wScroll*.00005);
if (wScroll <= pContainerHeight) {
$('.header_back').css({
'transform' : 'scale('+ wZoomOut +')'
});
$('.logo').css({
'transform' : 'translate(0px, '+ wScroll /0.7 +'%)'
});
}
最佳答案
修改代码后,我可以在滚动时获得平滑的视差缩小,但使用background-size
属性而不是transform: scale()
。我是这样做的:首先放大背景图像一点(例如105%
),然后在向下滚动时逐渐缩小到100%
。我还确保background-size
不会低于100%
以便它始终覆盖整个标题区域。
CSS
...
.header__back {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: url("http://www.adamkhourydesign.com/test/img/header_bg.jpg") top center no-repeat fixed;
background-size: 105%; /** the initial zoom **/
overflow: hidden;
}
...
Javascript
var height = $('#header_container').height();
var logo = $('.logo');
var background = $('.header__back');
$(window).on('scroll', function() {
var scroll = $(this).scrollTop();
logo.css('transform', 'translateY(' + scroll / 0.7 + '%)');
var backgroundSize = 105 - (5 - (height - scroll) / height * 5);
backgroundSize = backgroundSize < 100 ? 100 : backgroundSize;
background.css('background-size', backgroundSize + '%');
});
看看这把小提琴,看看它的作用:parallax zoom out demo