Javascript 当我滚动时如何使图像淡入淡出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27747970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make images fade visible when i'm scrolling
提问by Morten Buller Resen Kibsgaard
<div id="smiley">
<div id="star">
<img src="inc/img/heks.png" class="star">
<img src="inc/img/impo.png" class="star">
<img src="inc/img/angst.png" class="star">
</div>
</div>
#smiley{
margin: 50px auto 80px;
width: 1132px;
height: 300px;
}
#smiley #star{
display: none;
float: left;
height: 300px;
width: 1132px;
}
#smiley #star img.star{
display: block;
float: left;
width: 300px;
margin: 50px 38px 0px;
}
I need have the images to fade visible when i'm scrolling down to them.
当我向下滚动到它们时,我需要让图像褪色可见。
i hope you understand the question.
我希望你明白这个问题。
- This website template, does it http://www.templatemonster.com/demo/51771.html
回答by MujtabaFR
If you want to show the images only when they become in the window of browser.. without affecting their loading ..
如果您只想在浏览器窗口中显示图像.. 而不会影响它们的加载..
Try this, make the visibilityof image hidden, then using JavaScript add class fadeInto the image when it become in the window of browser ..
试试这个,使图像的可见性隐藏,然后使用 JavaScript在图像进入浏览器窗口时添加类淡入淡出..
So.. in your CSS:
所以.. 在你的CSS 中:
<style>
.star {
visibility: hidden;
}
.fadeIn {
-webkit-animation: animat_show 0.8s;
animation: animat_show 0.8s;
visibility: visible !important;
}
@-webkit-keyframes animat_show{
0%{opacity:0}
100%{opacity:1}
}
</style>
Then load jQuerylibrary
然后加载jQuery库
<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
and in your JavaScript:
并在您的JavaScript 中:
<script>
function showImages(el) {
var windowHeight = jQuery( window ).height();
$(el).each(function(){
var thisPos = $(this).offset().top;
var topOfWindow = $(window).scrollTop();
if (topOfWindow + windowHeight - 200 > thisPos ) {
$(this).addClass("fadeIn");
}
});
}
// if the image in the window of browser when the page is loaded, show that image
$(document).ready(function(){
showImages('.star');
});
// if the image in the window of browser when scrolling the page, show that image
$(window).scroll(function() {
showImages('.star');
});
</script>
Hope this will help you ..
希望能帮到你 ..
回答by Joe Sager
Check out my answer to this question: How to animate this when scrolled
查看我对这个问题的回答:滚动时如何设置动画
Also take a look at the website the OP linked to, it might have some animations you'd be interested in and also explains how to do different kinds of animations
还可以查看 OP 链接到的网站,它可能有一些您感兴趣的动画,还解释了如何制作不同类型的动画
Like others have said, make sure the element you want to fade in first has display: none
就像其他人所说的,确保您要先淡入的元素具有 display: none

