Javascript 如何在向下和向上滚动时触发 css 动画
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28307625/
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 Trigger css animation both on scrolling down and up
提问by David Martins
I'm using several CSS animations on a project. My problem is these animations get triggered only once, when scrolling down. I need them to be triggered every time the user scrolls by them, whether going up or down the page.
我在一个项目中使用了几个 CSS 动画。我的问题是这些动画在向下滚动时只触发一次。我需要在用户每次滚动时触发它们,无论是向上还是向下页面。
CSS
CSS
.slideRight{
animation-name: slideRight;
-webkit-animation-name: slideRight;
animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;
animation-timing-function: ease-in-out;
-webkit-animation-timing-function: ease-in-out;
visibility: visible !important;
}
@keyframes slideRight {
0% {
transform: translateX(-150%);
}
50%{
transform: translateX(8%);
}
65%{
transform: translateX(-4%);
}
80%{
transform: translateX(4%);
}
95%{
transform: translateX(-2%);
}
100% {
transform: translateX(0%);
}
}
@-webkit-keyframes slideRight {
0% {
-webkit-transform: translateX(-150%);
}
50%{
-webkit-transform: translateX(8%);
}
65%{
-webkit-transform: translateX(-4%);
}
80%{
-webkit-transform: translateX(4%);
}
95%{
-webkit-transform: translateX(-2%);
}
100% {
-webkit-transform: translateX(0%);
}
}
HTML
HTML
<div class="animation-test element-to-hide" style="visibility:visible;">Something</div>
JavaScript
JavaScript
$(window).scroll(function() {
$('.animation-test').each(function(){
var imagePos = $(this).offset().top;
var topOfWindow = $(window).scrollTop();
if (imagePos < topOfWindow+400) {
$(this).addClass("slideRight");
}
});
});
$('.element-to-hide').css('visibility', 'hidden');
回答by apaul
Something like this should work.
像这样的事情应该有效。
$(window).scroll(function () {
$('.animation-test').each(function () {
var imagePos = $(this).offset().top;
var imageHeight = $(this).height();
var topOfWindow = $(window).scrollTop();
if (imagePos < topOfWindow + imageHeight && imagePos + imageHeight > topOfWindow) {
$(this).addClass("slideRight");
} else {
$(this).removeClass("slideRight");
}
});
});
Basically its just using an if statement to find whether the element is within the view port and adding and removing the class. You can toggle the visibility of the element by using:
基本上它只是使用 if 语句来查找元素是否在视口内并添加和删除类。您可以使用以下方法切换元素的可见性:
.element-to-hide{
visibility:hidden;
}
.slideRight {
visibility: visible;
animation-name: slideRight;
-webkit-animation-name: slideRight;
animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;
animation-timing-function: ease-in-out;
-webkit-animation-timing-function: ease-in-out;
}

