【问题标题】:Typewriter effect in Angular 2Angular 2 中的打字机效果
【发布时间】:2016-12-22 15:44:17
【问题描述】:

我一直在尝试在 Angular2 中创建打字机效果。

我的问题基本上是什么是最好的方法。我能够做到这一点的唯一方法是通过 CSS 动画。这还没有给我想要的结果。到目前为止,我已经尝试了三种方法。

CSS 方法

创建了一个带有单独样式表的组件。

@import url(http://fonts.googleapis.com/css?family=Anonymous+Pro);

.typewriter h2 {
    margin: 0 auto;
    border-right: .15em solid white;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    transform: translateY(-50%);
    animation: typewriter 2.5s steps(28) 1s 1 normal both,
             blinkTextCursor 500ms steps(28) infinite normal;
}

@keyframes typewriter{
  from { width: 0 }
  to { width: 100% }
}

@keyframes blinkTextCursor{
  from{border-right-color: rgba(255,255,255,.75);}
  to{border-right-color: transparent;}
}

#typewriterbox {
  display: inline-block;
}

接下来是要添加组件的 HTML。

<div class="page-title">
    <animated-typing>CSS Typewriter effect</animated-typing>
</div>

还有组件文件:

import {Component} from '@angular/core'

@Component({
  moduleId: module.id,
  selector : 'animated-typing',
  styleUrls: ['animated-typing.component.css'],
  template: `<div id="typewriterbox" class="typewriter"><h2><ng-content></ng-content></h2></div>`
})

export class AnimatedTypingComponent {}

然后我尝试了其他两种方法,这两种方法都不起作用。这基本上只是意味着在我的 index.html 中添加一个脚本。

Javascript 方法

这是我从 codepen 获得的一些打字机代码。 http://codepen.io/gavra/pen/tEpzn

这部分在获取 HTML 时失败。

var destination = document.getElementById("typedtext");

脚本使用 getElementById,它返回 null。然后在尝试设置destination.value 时中断。根据我目前的理解,这不是要走的路,但我想看看是否有可能。

<script type="text/javascript" src="js/test.js"></script>

// set up text to print, each item in array is new line
var aText = new Array(
"There are only 10 types of people in the world:", 
"Those who understand binary, and those who don't"
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines

var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row

function typewriter()
{
 sContents =  ' ';
 iRow = Math.max(0, iIndex-iScrollAt);
 var destination = document.getElementById("typedtext");

 while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '<br />';
 }
 destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
 if ( iTextPos++ == iArrLength ) {
  iTextPos = 0;
  iIndex++;
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length;
   setTimeout("typewriter()", 500);
  }
 } else {
  setTimeout("typewriter()", iSpeed);
 }
}


typewriter();

最后,我认为这是“Angular”的意图。但是,我无法使其正常工作。这意味着“typerwiter”代码在组件 ts 文件中。或者也许通过指令。由于“所有有效的 javascript 代码”也应该在 typescript 中工作,我只是复制了 javascript。不过还没有。

Angular2 方法

这是我创建的组件文件。在搞清楚 Angular 2 的同时,我也在学习 typescript 的新知识。它给出了打字机功能的参考错误。模板中的 HTML 部分与之前保持一致。

import {Component} from '@angular/core';

@Component({
  moduleId: module.id,
  selector : 'animated-typing',
  template: `<div><h2><ng-content></ng-content></h2></div>`,
  host: {
    'id':'typedtext'
  }
})

export class AnimatedTypingComponent {

  constructor(){
    typewriter();
  }

}

function typewriter()
{
  // set up text to print, each item in array is new line
  var aText = new Array(
  "I",
  "Love",
  "to",
  "Code."
  );
  var iSpeed = 100; // time delay of print out
  var iIndex = 0; // start printing array at this posision
  var iArrLength = aText[0].length; // the length of the text array
  var iScrollAt = 20; // start scrolling up at this many lines

  var iTextPos = 0; // initialise text position
  var sContents = ''; // initialise contents variable
  var iRow; // initialise current row
  sContents =  ' ';
  iRow = Math.max(0, iIndex-iScrollAt);

  var destination = document.getElementById("typedtext");

  while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '<br />';
  }
  destination.innerText = sContents + aText[iIndex].substring(0, iTextPos) + "_";
  if ( iTextPos++ == iArrLength ) {
  iTextPos = 0;
  iIndex++;
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length;
   setTimeout("typewriter()", 500);
  }
  } else {
  setTimeout("typewriter()", iSpeed);
  }
}

最后,我添加了 app.module.ts 以作为衡量标准。组件的导入位置:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { AppComponent }  from './app.component';
import { AnimatedTypingComponent } from './components/features/animated-typing.component';

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent, AnimatedTypingComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    我最近为我的网站实现了这个。这是我的做法:

    1. 创建以下两个变量:

      private typewriter_text: string = "Thank you for your interest";
      private typewriter_display: string = "";
      
    2. 创建一个连续的自调用函数:

      typingCallback(that) {
        let total_length = that.typewriter_text.length;
        let current_length = that.typewriter_display.length;
        if (current_length < total_length) {
          that.typewriter_display += that.typewriter_text[current_length];
          setTimeout(that.typingCallback, 100, that);
        } else {
          that.typewriter_display = "";
        }
      }
      
    3. 在 angular2 ngOnInit() 中调用自调用函数,启动它:

      ngOnInit() {
        this.typingCallback(this);
      }
      
    4. 以下内容必须出现在 HTML 中的某处

      {{typewriter_display }}
      

    【讨论】:

      【解决方案2】:

      您可以使用T-Writer.js 包。

      安装包:

      $ npm install t-writer.js --save
      
      

      您的 TS 代码:

      import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
      import Typewriter from 't-writer.js';
      
      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent implements OnInit, AfterViewInit {
        name = 'Angular';
        @ViewChild('tw') typewriterElement;
        @ViewChild('tw2') typewriterElement2;
        @ViewChild('tw3') typewriterElement3;
      
        ngOnInit() {
      
         }
        ngAfterViewInit() {
          const target2 = this.typewriterElement2.nativeElement;
          const target3 = this.typewriterElement3.nativeElement;
          const target = this.typewriterElement.nativeElement
      
          const writer = new Typewriter(target, {
            loop: true,
            typeColor: 'blue'
          })
      
          writer
            .type(`Without washing the brush, I'm gonna go right into some Van Dyke Brown, some Burnt Umber, and a little bit of Sap Green. Maybe he has a little friend that lives right over here. Maybe there was an old trapper that lived out here and maybe one day he went to check his beaver traps, and maybe he fell into the river and drowned.
      
      Get away from those little Christmas tree things we used to make in school. You want your tree to have some character. Make it special. Just make little strokes like that. We'll put a happy little sky in here. See. We take the corner of the brush and let it play back-and-forth.
      
      You have to make almighty decisions when you're the creator. Just go out and talk to a tree. Make friends with it. Let's have a little bit of fun today. Remember how free clouds are. They just lay around in the sky all day long. This is probably the greatest thing that's ever happened in my life.
      
      Imagination is the key to painting. A beautiful little sunset. God gave you this gift of imagination. Use it. There are no limits in this world.
      
      You can't have light without dark. You can't know happiness unless you've known sorrow. Maybe there's a happy little waterfall happening over here. As trees get older they lose their chlorophyll. Isn't that fantastic that you can make whole mountains in minutes? This is the time to get out all your flustrations, much better than kicking the dog around the house or taking it out on your spouse.
      
      Almost everything is going to happen for you automatically - you don't have to spend any time working or worrying. Water's like me. It's laaazy ... Boy, it always looks for the easiest way to do things Maybe there's a happy little Evergreen that lives here. You got your heavy coat out yet? It's getting colder. Every time you practice, you learn more.
      
      Don't forget to tell these special people in your life just how special they are to you. These trees are so much fun. I get started on them and I have a hard time stopping. If I paint something, I don't want to have to explain what it is.
      
      `)
            .rest(500)
            .start()
      
          const writer2 = new Typewriter(target2, {
            typeColor: 'blue'
          })
          const writer3 = new Typewriter(target3, {
            typeColor: 'red'
          })
      
        writer2
        .type('Combo typewriters to')
        .removeCursor()
        .then(writer3.start.bind(writer3))
        .start()
      
      writer3
        .type("create complex effects")
        .rest(500)
        .clear()
        .changeTypeColor('red')
        .type("defy user expectations")
        .rest(500)
        .clear()
        .changeTypeColor('blue')
        .type("generate a custom loop")
        .rest(500)
        .clear()
        .changeTypeColor('black')
        .then(writer2.start.bind(writer2))
        }
      }
      
      
      

      HTML 标记

      <hello name="{{ name }}"></hello>
      <div class="beside"> <span class="tw" #tw2> </span><span #tw3></span> </div>
      
      <h1 class="tw" #tw></h1>
      

      【讨论】:

        【解决方案3】:

        如果要停止重新加载,请将“typingCallback”函数更改为:

        typingCallback(that) {
        
          let total_length = that.typewriter_text.length;
          let current_length = that.typewriter_display.length;
          if (current_length < total_length) {
            that.typewriter_display += that.typewriter_text[current_length];
            setTimeout(that.typingCallback, 100, that);
          }  
        }
        

        【讨论】:

          猜你喜欢
          • 2016-08-31
          • 1970-01-01
          • 2020-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-30
          • 1970-01-01
          相关资源
          最近更新 更多