Aji*_*ith 15 html javascript jquery animation css3
我已经在我的html页面上为各种div元素添加了CSS动画.但是所有动画同时播放并且我无法在页面底部看到动画.如何在向下滚动页面时让它们播放?
Rok*_*jan 28
你需要使用JS或jQuery的,以触发您的CSS3过渡/动画
一旦元素是视**.
听load
,resize
和scroll
事件,以获得一个元素是否进入视口.
您可以使用我构建的小型jQuery插件:(/sf/answers/1878177941/)
假设您有像以下一样的动画框:
<div class="box rotate"></div>
<div class="box scale"></div>
<div class="box translate"></div>
Run Code Online (Sandbox Code Playgroud)
比你的CSS有:
.box{
width:300px;
height:300px;
margin:500px 50px;
background:red;
transition: 1.5s; /* THE DURATION */
}
.rotate.triggeredCSS3 {transform : rotate(360deg); }
.scale.triggeredCSS3 {transform : scale(1.6); }
.translate.triggeredCSS3 {transform : translate3d(400px,0,0); }
Run Code Online (Sandbox Code Playgroud)
其中.triggeredCSS3
将由插件动态分配:
$(".box").inViewport(function(px){
if(px) $(this).addClass("triggeredCSS3") ;
});
Run Code Online (Sandbox Code Playgroud)
Adr*_*ano 24
仍然是 Javascript,但在这个版本中你不需要监听滚动事件。速度和性能比每次检查对象是否在视口中要好得多。
检查这个:https : //developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
使用Intersection Observer,您可以在元素可见时定义回调。
选项:
root
: null << 如果您希望它在您的视口(可见区域)内,请设置为 null
threshold
: 0.3 << 表示 30% 的可见性。如果设置为 0.3,则在可见性达到至少 30% 时调用一次回调,并且在可见性低于 30% 时调用一次回调。
function callbackFunc(entries, observer)
{
entries.forEach(entry => {
var txt = entry.target.id + " visibility: " + entry.isIntersecting;
document.getElementById('log').appendChild(document.createTextNode(txt));
document.getElementById('log').appendChild(document.createElement("br"));
});
}
let options = {
root: null,
rootMargin: '0px',
threshold: 0.3
};
let observer = new IntersectionObserver(callbackFunc, options);
observer.observe(document.getElementById('firstBlock'));
observer.observe(document.getElementById('secondBlock'));
Run Code Online (Sandbox Code Playgroud)
#firstBlock {
width: 50vw;
height: 80vh;
background: red;
}
#secondBlock {
width: 50vw;
height: 80vh;
background: blue;
}
#log {
width: 200px;
height: 80vh;
position: fixed;
right: 0px;
top: 10px;
overflow: auto;
}
Run Code Online (Sandbox Code Playgroud)
First Block:
<div id='firstBlock'> </div>
<br><br><br>
Second Block:
<div id='secondBlock'> </div>
<div id='log'>Log: </div>
Run Code Online (Sandbox Code Playgroud)