我有这个方块:
我想在图片上创建视差效果,同时将图片保持在(或至少靠近)其父div。
这在我的代码中:
<div class="head-block">
<div class="image-block-left">
= image_tag('home/specialite-1-compressor.jpg', id: 'block-left-specialite1')
= image_tag('home/specialite-2-compressor.jpg', id: 'block-left-specialite2')
</div>
<div class="content-block">
span.badge.badge-warning.homepage-badge
| Expertise
.homepage-title
h2
| Lorem ipsum dolor sit amet, consectetur adipiscing elit.
p
| Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla mollis feugiat libero quis mollis. Praesent risus purus, pellentesque in risus at, posuere laoreet eros. Ut non congue erat. Pellentesque tincidunt ultrices leo vel porttitor. Fusce a ligula ut libero aliquet feugiat. Nulla facilisi. Curabitur consectetur eu quam vel blandit. In non enim quis justo malesuada volutpat.
</div>
<div class="image-block-right">
= image_tag('home/specialite-3-compressor.jpg', id: 'block-left-specialite3')
= image_tag('home/specialite-4-compressor.jpg', id: 'block-left-specialite4')
</div>
</div>
.head-block {
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
.image-block-left {
position: relative;
width: 17.5%;
img:nth-child(1) {
width: 150px;
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
img:nth-child(2) {
height: 180px;
position: absolute;
top: 100px;
right: 0;
z-index: 1;
}
}
.content-block {
width: 65%;
text-align: center;
}
.image-block-right {
position: relative;
width: 17.5%;
img:nth-child(1) {
height: 200px;
position: absolute;
top: 0;
right: 0;
}
img:nth-child(2) {
width: 130px;
position: absolute;
top: 155px;
left: 0;
}
}
}
我尝试了以下代码:
function parallaxEffect() {
let scrolled = $(window).scrollTop();
$('#block-left-specialite1').css('top', (0 - (scrolled * .5)) + 'px');
$('#block-left-specialite2').css('top', (100 - (scrolled * .65)) + 'px');
$('#block-left-specialite3').css('top', (0 - (scrolled * .52)) + 'px');
$('#block-left-specialite4').css('top', (155 - (scrolled * .67)) + 'px');
}
,但是它不起作用,因为head-block
div不在页面顶部。如何将图像保留在其父div内?
答案 0 :(得分:0)
最后,我是通过这种方式实现的:
function parallaxEffect() {
let windowScrolled = $(window).scrollTop();
let sliderBlockScrolled = $('.homepage-sliderblock').offset().top;
$('.top-block-right').css('top', (0 - (windowScrolled * .25)) + 'px');
$('#block-left-specialite1, #block-left-specialite3').css('top', (0 - ((windowScrolled - sliderBlockScrolled) * .25)) + 'px');
$('#block-left-specialite2, #block-left-specialite4').css('top', (100 - ((windowScrolled - sliderBlockScrolled) * .35)) + 'px');
}
因此,当父div可见时,元素与视差效果处于同一级别。