Я пытаюсь создать эффект пишущей машинки в Angular2.Эффект пишущей машинки в Angular 2
Мой вопрос в основном заключается в том, что это лучший подход. Единственный способ, которым я смог это сделать, - это анимирование 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();
Тогда, наконец, подход, который, как я думаю, предназначен для «Углового». Однако я не смог добиться этого. Значение кода «typerwiter» находится в файле компонента ts. Или, может быть, через директиву. Поскольку «все допустимые javascript-коды» также должны работать в машинописном тексте, я просто скопировал javascript. Пока ничего.
Angular2 подход
Это компонент файла я создал. Выяснив Угловое 2, я также разбираюсь в машинописных текстах. Он дает опорную ошибку для функции пишущей машинки. Часть 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 { }