我首先要说的是,我对css还很陌生,所以如果我的问题的答案很明显,请原谅我。我希望将效果应用于屏幕中最居中的元素。我希望用户向下滚动,让照片从灰度级饱和。
这是我希望效果发生在的页面:
http://evanscottpierce.com/portfolio/
当前的桌面行为是在悬停时饱和,但显然这对移动设备不起作用,所以我希望通过滚动来触发饱和。正如你在下面看到的,我只是将灰度效果应用到桌面上,直到我可以为移动设备获得所需的行为。
这是我迄今为止的代码:
@media only screen and (min-width:768px){
.gray-scale-img .rl-gallery {
overflow: hidden;
-webkit-backface-visibility: hidden;
}
.gray-scale-img .rl-gallery .rl-gallery-link {
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
-webkit-transition: .3s ease-in-out;
transition: .3s ease-in-out;
will-change: filter;
}
.gray-scale-img .rl-gallery .rl-gallery-link:hover {
-webkit-filter: grayscale(0);
filter: grayscale(0);
}
}
提前谢谢!
使用helper方法来选择是否应该应用css,然后将该css与class一起应用是非常干净的。
// loop to add sample images
let imageCount = 0;
while (imageCount++ < 10) {
$('body').append('<p><img src="https://picsum.photos/200/100?image=' + imageCount + '" alt="sample image" class="gray-scale-img" ></p>');
}
// helper function to check for vertical centering
function isScrolledIntoCenter(elem)
{
var docViewCenter = $(window).scrollTop() + $(window).height() / 2;
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewCenter) && (elemTop <= docViewCenter));
}
// function to toggle .in-color based on visibility
function toggleInColor() {
const images = $('img.gray-scale-img');
images.each(function() {
$(this).toggleClass('in-color',isScrolledIntoCenter(this));
});
}
toggleInColor();
$(window).on('scroll', toggleInColor);
.gray-scale-img {
-webkit-backface-visibility: hidden;
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
-webkit-transition: .3s ease-in-out;
transition: .3s ease-in-out;
will-change: filter;
}
.gray-scale-img.in-color {
-webkit-filter: grayscale(0);
filter: grayscale(0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
最简单的方法是使用css3-flexbox:
<div class="flex-container">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>
<div>Six</div>
<div>Seven</div>
<div>Eight</div>
<div>Nine</div>
</div>
<style type="text/css">
.flex-container {
display:flex;
height: 200px;
align-items: center;
}
</style>