首页 > 解决方案 > 飞入动画仅在焦点上

问题描述

我想在 Angular 应用程序中仅在具有特定类(而不是页面加载)的块的焦点上创建飞入效果。这可能没有 jquery 或其他库(我搜索但实际上只找到了带有 jquery 的解决方案,我没有在我的 Angular 应用程序上使用它)。我用 Angular 标签问是因为我在一个 Angular 应用程序中,但也许还有一种只使用 css 的方法?

一个不适用于焦点但在页面加载上的示例:

#first-page {
  height: 100vh;
  background-color: red;
  color: white;
  line-height: 100%;
}
#second-page {
  height: 100vh;
  background-color: green;
  color: white;
  line-height: 100%;
}
.fly-in-block {
  background-color: blue;
  width: 100px;
  height: 100px;
  margin: 100px auto;
  transform: translateX(-600%);
  -webkit-transform: translateX(-600%);
}
.flyIn {
  animation: flyIn 0.8s forwards;
  -webkit-animation: flyIn 0.8s forwards;
}
@keyframes flyIn {100% { transform: translateX(0%); }}
@-webkit-keyframes flyIn {100% { -webkit-transform: translateX(0%); }}
<div id="first-page">
  First page
</div>
<div id="second-page">
  Second page
  <div class="fly-in-block flyIn"></div>
</div>

这里是 Angular 片段的链接: https://stackblitz.com/edit/angular-fly-in-animation-on-focus?file=src%2Fapp%2Fapp.component.css

标签: javascriptcssangularsass

解决方案


我不确定你所说的专注是什么意思。你在寻找这样的东西吗?您可能可以根据需要对其进行调整。

在 html 中查看我删除了flyIn该类并仅在块滚动到视图时通过 js 添加它。

一旦动画被触发,监听器就会被移除。

const block = document.querySelector( '.fly-in-block' )
const blockOffset = block.offsetTop

const triggerAnimation = () => {
  const scrollHeight = document.body.scrollHeight
  if( scrollHeight >= blockOffset ) {
    block.classList.add( 'flyIn' )
    window.removeEventListener( 'scroll', triggerAnimation )
  }
}

window.addEventListener( 'scroll', triggerAnimation )
#first-page {
  height: 100vh;
  background-color: red;
  color: white;
  line-height: 100%;
}
#second-page {
  height: 100vh;
  background-color: green;
  color: white;
  line-height: 100%;
}
.fly-in-block {
  background-color: blue;
  width: 100px;
  height: 100px;
  margin: 100px auto;
  transform: translateX(-600%);
  -webkit-transform: translateX(-600%);
}
.flyIn {
  animation: flyIn 0.8s forwards;
  -webkit-animation: flyIn 0.8s forwards;
}
@keyframes flyIn {100% { transform: translateX(0%); }}
@-webkit-keyframes flyIn {100% { -webkit-transform: translateX(0%); }}
<div id="first-page">
  First page
</div>
<div id="second-page">
  Second page
  <div class="fly-in-block"></div>
</div>


推荐阅读