我正在创建一个CV页面,其中包含动画-其中一些可以与其他库一起使用:Animate CSS。它可以工作,但是动画是在页面完全加载后开始的-我希望它们在滚动到div开始的位置(位于页面中间)时发生。
我尝试使用元素.scrollTop
来做到这一点,但是然后我只能在px中包含值-并且我需要响应页面(我使用calc()
)
还有可能我做错了什么-但我没有注意到
就像我说的那样-当div进入视线范围时,我想开始制作动画。
答案 0 :(得分:0)
如果您将JQuery与JavaScript DOM或仅与JavaScript DOM结合使用,则这是可能的。
我的功能可能不是最好的方法,但是它可以工作并且非常简单。
我的示例在相对于视口的灰色div顶部偏移小于100时启动了Animation。
(如果要使用此方法,请制作2个CSS类(1个带有动画,1个不带有动画,并将ID字符串设置为HTML ID)
.Initial{
background-color: #ccc;
color: black;
position: fixed;
}
.AfterScroll{
background-color: #fff;
color: green;
position: fixed;
animation-name: Anim;
animation-duration: 1.4s;
}
@keyframes Anim{
25% {color: red;}
50% {color: blue;}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript">
$( "#AnimationElementID" ).addClass("AfterScroll");
var set = false; // will be false on page load
$( window ).scroll(function() { //On Scroll Event Handler, Could also be window.onscroll (DOM)
// JS HTML DOM get element position relative to viewport
var rect = document.getElementById("AnimationElementTriggerDivID").getBoundingClientRect();
// This is the offset at where your animation would start, 100 = div is 100px from viewport top
if( rect.top <100 && set==false){
$( "#AnimationElementID" ).toggleClass("Initial");
$( "#AnimationElementID" ).toggleClass("AfterScroll");
set=true; // so we only toggle the class once
}
});
</script>
</head>
<body>
<p class="Initial" id="AnimationElementID">
Hi im a text and I will change color if you scroll
</p>
<div id="AnimationElementTriggerDivID" style="background-color: #ccc; position: relative; top:200px; width:20px; height:2000px"> </div>
</body>
</html>
也许其他人可以提供更好的“仅JQuery”选项或更简洁的功能,但在此之前,请随时使用。
PS:如果可能,请提供代码段,以便人们能够更好,更快地为您提供帮助。