首页 > 解决方案 > 准备就绪时聚合物 3 中的淡入过渡

问题描述

我希望在加载聚合物 3 中的视图时淡入 div 元素。我尝试通过在 div 中添加一个 opacity: 0 的 css 类来解决这个问题。聚合物模板准备好后,应删除 css 类并开始 css 转换(在 2 秒内将不透明度转换为 0),但不执行转换,仅在加载页面时 div 可见。

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import './shared-styles.js';

class MyView1 extends PolymerElement {
  static get template() {
    return html`
      <style include="shared-styles">
        :host {
          display: block;
          padding: 10px;
        }

      .card{
        opacity: 1;
        transition: 2s opacity;
      }

      .fade-out {
        opacity: 0;
      }
      </style>
      <button on-click="fadeIn">click</button>
      <div class="card fade-out" id="myCard">
        <div class="circle">1</div>
        <h1>View One</h1>
        <p>Ut labores minimum atomorum pro. Laudem tibique ut has.</p>
        <p>Lorem ipsum dolor sit amet, per in nusquam nominavi periculis, sit elit oportere ea.Lorem ipsum dolor sit amet, per in nusquam nominavi periculis, sit elit oportere ea.Cu mei vide viris gloriatur, at populo eripuit sit.</p>
      </div>
    `;
  }


  ready() {
    super.ready();
    console.log("ready");
    this.fadeIn(); //not working
  }

  fadeIn(){
    console.log("fade-in");
    this.$.myCard.classList.remove("fade-out");
  }
}

window.customElements.define('my-view1', MyView1);

标签: polymerpolymer-3.x

解决方案


纯 CSS 解决方案:

这是我使用并从 SO 获得的,尽管我找不到原始帖子。

将它放在共享样式中并添加要在页面转换中淡入淡出的元素的类:

  @keyframes fade-in-right {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  .card, .otherelementtofade, .yetanotherelementtofade{
      opacity: 0;
      animation: fade-in-right ease 0.4s forwards;
  }

正如 peeh 所说,您可以将其结合起来以包含幻灯片效果:

  @keyframes fade-in-right {
    from {
      opacity: 0;
      transform: translateX(-15px);
    }
    to {
      opacity: 1;
      transform: translateX(0);
    }
  }

  .card, .otherelementtofade, .yetanotherelementtofade{
      opacity: 0;
      animation: fade-in-right ease 0.4s forwards;
  }

推荐阅读