Mat*_*rix 6 javascript css jquery animation css3
HTML元素一出现在屏幕上就会如何设置动画?
我在堆栈溢出浏览页面上找到了一个示例,只要向下滚动足够远,信息元素就会滑入页面.这背后的诀窍是什么?
为此,您可以使用交集观察者。Intersection Observer API 提供了一种异步观察目标元素与祖先元素或顶级文档视口相交变化的方法。
const startAnimation = (entries, observer) => {
entries.forEach(entry => {
entry.target.classList.toggle("slide-in-from-right", entry.isIntersecting);
});
};
const observer = new IntersectionObserver(startAnimation);
const options = { root: null, rootMargin: '0px', threshold: 1 };
const elements = document.querySelectorAll('.card');
elements.forEach(el => {
observer.observe(el, options);
});Run Code Online (Sandbox Code Playgroud)
.card {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.slide-in-from-right {
animation: 1.5s ease-out 0s 1 slideInFromRight forwards;
}
@keyframes slideInFromRight {
0% {
transform: translateX(50%);
}
100% {
transform: translateX(0);
}
}Run Code Online (Sandbox Code Playgroud)
<div class="card">
<h2>Card one</h2>
</div>
<div class="card">
<h2>Card two</h2>
</div>
<div class="card">
<h2>Card three</h2>
</div>Run Code Online (Sandbox Code Playgroud)
您需要使用javascript来检测视口的位置,并在视口可见时将其激活.
您可以使用javascript来检测并执行转换,然后使用css或javascript来制作动画.
有许多基于jquery的脚本可用于实现此目的.这是一个例子:
1.创建一个Html元素,你要检查它是否在视口中.
<div class="demo"></div>
Run Code Online (Sandbox Code Playgroud)
2.在文档末尾加载jQuery javascript库和jQuery Viewport Checker插件.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="viewportchecker.js"></script>
Run Code Online (Sandbox Code Playgroud)
3.在这个元素上调用插件并在javascript中执行一些操作.
<script>
$(document).ready(function(){
$('.demo').viewportChecker({
// Class to add to the elements when they are visible
classToAdd: 'visible',
// The offset of the elements (let them appear earlier or later)
offset: 100,
// Add the possibility to remove the class if the elements are not visible
repeat: false,
// Callback to do after a class was added to an element. Action will return "add" or "remove", depending if the class was added or removed
callbackFunction: function(elem, action){}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)