我想不使用创建的视差效果background-image
有background-attachment: fixed
,因为background-attachment: fixed
没有在iOS上工作这么好。这是我想出的:
<article class="twentyseventeen-panel">
<div class="panel-image">
<div style="position: absolute; top: 0; bottom: 0; left: 0; right: 0;" >
<img src="<?php echo esc_url( $thumbnail[0] ); ?>" style="width: 100%;" />
</div>
</div>
</article>
.twentyseventeen-panel {
overflow: hidden;
position: relative;
}
.panel-image {
position: relative;
height: 100vh;
max-height: 200px;
}
现在,我被困在图像滚动以执行视差效果。我尝试将图像设置为一个fixed
位置,但是这样做后我的图像不再显示。如何获得具有视差效果的图像?
不幸的是,我不知道使用纯CSS的确切方法。这样做的原因是因为无法获取当前的滚动位置(我们可能在中使用它calc()
)。同样,在使用定位元素时fixed
,它不再关心其父元素,并且无法强制使用overflow:hidden
。
在不使用背景的情况下,有两种创建视差效果的方法,一种是利用JavaScript,一种是完整的示例。它很小,可能会使浏览器无法正常工作,但它可以工作。当然,您将需要对其进行优化,使其仅适用于拥有很多元素的可见元素。
$(document).ready(function() {
var onScroll = function() {
var scrollTop = $(this).scrollTop();
$('.paralax-image').each(function(index, elem) {
var $elem = $(elem);
$elem.find('img').css('top', scrollTop - $elem.offset().top);
});
};
onScroll.apply(window);
$(window).on('scroll', onScroll);
});
.content {
height: 500px;
}
.paralax-image {
overflow: hidden;
height: 200px;
position: relative;
}
.paralax-image img {
position: absolute;
height: 100vh;
min-width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<h2>Lorem Ipsum</h2>
<div class="paralax-image">
<img src="http://placehold.it/400x200">
</div>
</div>
现在到完整的CSS部分...实现起来有点复杂,并且无法针对每种布局进行。诀窍是让您的图片使用position:fixed
规则。但是overflow:hidden
,您可以让它们处于最低的z-index,让所有元素具有背景,并在要显示图像的位置创建“孔”,而不是不完全依赖。添加背景时,这将带来很多问题,您必须制作多个不同的元素以确保始终可以显示视差图像。我试图演示如何实现这一目标,而不用创建过于复杂的示例。此技术仅适用于1张图像。如果您希望它可以处理多张图片,则必须使用javascript相应地切换可见性,
/* Can't use margins no more... */
h1 {
margin: 0;
padding: 0.67em 0;
}
p {
margin: 0;
padding: 1em 0 0;
}
body {
margin: 0;
}
.container>* {
background-color: white;
}
.paralaxed {
z-index: -2;
height: 100vh;
position: fixed;
top: 0;
}
.paralax-image {
background: transparent;
height: 200px;
}
<div class="container">
<img class="paralaxed" src="http://placehold.it/400x200">
<h1>My Title here</h1>
<div class="paralax-image"></div>
<p>
lorem ipsum...
</p>
<p>
lorem ipsum...
</p>
<p>
lorem ipsum...
</p>
<p>
lorem ipsum...
</p>
<p>
lorem ipsum...
</p>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句