【发布时间】:2020-10-15 08:08:22
【问题描述】:
我想在我的 Angular 项目中使用此代码:
'use strict';
/**
* Floating text animation (random)
*/
angular.module('g1b.text-animation', []).
directive('textAnimation', ['$document', '$interval', '$timeout', function ($document, $interval, $timeout) {
return {
restrict: 'A',
compile: function () {
return {
pre: function () {},
post: function (scope, element) {
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
$interval(function () {
for ( var i = 0; i < Math.floor(Math.random() * 5); i++ ) {
var character = chars[Math.floor(Math.random() * chars.length)];
var duration = Math.floor(Math.random() * 15);
var offset = Math.floor(Math.random() * (45 - duration * 3)) + 3;
var size = 12 + (15 - duration);
var span = angular.element('<span class="animated-text" style="right:'+offset+'vw; font-size: '+size+'px; animation-duration:'+duration+'s">'+character+'</span>');
element.append(span);
$timeout(function (span) {
span.remove();
}, duration * 1000, false, span);
}
}, 250);
}
};
}
};
}]);
它还有一个 CSS 文件。 这段代码基本上是一个文本动画。 我的问题是我不知道从哪里开始。
这就是我想要实现的目标: https://rawgit.com/g1eb/angular-text-animation/master/
这是它的 npm: https://github.com/g1eb/angular-text-animation
更新:
我自己试过了,这就是我所拥有的:
@ViewChildren('styleDiv', {read: ElementRef}) children: QueryList<ElementRef>;
constructor(private renderer: Renderer2, private host: ElementRef) {
}
ngOnInit(): void {
}
ngAfterViewInit(): void {
this.animateBackground();
}
private animateBackground(): void {
const renderer = this.renderer;
const children = this.children;
const host = this.host;
const chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
setInterval(() => {
for (let i = 0; i < Math.floor(Math.random() * 5); i++) {
const character = chars[Math.floor(Math.random() * chars.length)];
const duration = Math.floor(Math.random() * 15);
const offset = Math.floor(Math.random() * (45 - duration * 3)) + 3;
const size = 12 + (15 - duration);
const span = '<span class="animated-text" style="right:' + offset + 'vw; font-size: ' +
+size + 'px; animation-duration:' + duration + 's">' + character + '</span>';
this.children.first.nativeElement.insertAdjacentHTML('beforeend', span);
setTimeout(() => {
// renderer.removeChild(children.first.nativeElement.parentNode, children.first.nativeElement);
}, duration * 1000, false, host, children, renderer);
}
}, 250, host, children, renderer);
}
它有效,但我在设置超时函数内部确实有问题。 我可以将跨度添加到 dom,但无法将其删除。
【问题讨论】:
-
angular js 和当前的 angular (2+) 运行方式非常不同,我不建议尝试更改用于 angular js 的包以适应。即使你设法让指令工作,底层的 css 很可能是在假设从指令生成的结果 html 将遵循 angularjs 框架下创建的,需要大量重写以适应它。最好尝试找到一个现有的 angular (2+) 包或从头开始编写一个包。
-
thx... 我会尝试从头开始写一些东西。
标签: angularjs angular angularjs-directive angular-directive