gpt4 book ai didi

javascript - 在特定滚动位置激事件画

转载 作者:行者123 更新时间:2023-11-27 23:56:29 26 4
gpt4 key购买 nike

我正在创建一个 CV 页面,其中包含动画 - 其中一些动画与其他库一起使用:Animate css。它有效,但动画在页面完全加载时开始 - 我希望它们在滚动到 div 开始的位置时发生(它在页面中间)

我已经尝试使用元素 .scrollTop 来做到这一点,但是我只能在 px 中包含值 - 我需要响应页面(我使用 calc() )也有可能我做错了什么 - 但我没有注意到

就像我说的 - 我想在 div 进入视线范围内时开始动画。

最佳答案

如果将 JQuery 与 JavaScript DOM 或仅与 JavaScript DOM 结合使用,这是可能的。

我的功能可能不是最好的方法,但它可以工作并且相当简单。

我的示例在灰色 div 相对于视口(viewport)的顶部偏移量低于 100 时启动动画。

(如果你想使用这个制作 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 only 选项,或者更简洁的函数,但在那之前,请随意使用它。

PS:如果可能,请提供代码片段,以便人们能够更好更快地帮助您。

关于javascript - 在特定滚动位置激事件画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56236905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com