我想在我的 Angular 应用程序中创建一个文本滚动条来显示通知。文本必须从右向左滑动。 我尝试了默认的 html 元素
<marquee>
,但是运行起来并不顺利,因此搜索了 CSS 动画,这样应该可以创建平滑的滚动文本。
为了将其完美地集成到我的应用程序中,我找到了角度动画。
滚动器现在可以正常工作,但并不完美,我无法让它正常工作。
我用我现在拥有的代码创建了一个小型 Stackblitz: https://stackblitz-starters-h6pnhs.stackblitz.io
通知的长度没有限制,因此总长度可能会有所不同。此外,通知的文本通常比示例中的文本长一点(示例中的通知只是一些人工智能幽默)。 想想:
'Sync with application X failed with status 500: [error message] - 2023-10-05 08:45'
我想要一个从右侧第一个字母开始并滚动到左侧最后一个字母的文本。之后动画应该重复。
要在 Angular 中创建平滑的滚动文本效果,您可以将 CSS 动画与 Angular 的动画模块结合使用。我提供了一个使用您的 StackBlitz 设置的示例:
<div class="notification-container">
<div *ngFor="let notification of notifications" class="notification-item">
{{ notification }}
</div>
</div>
.notification-container {
width: 300px; /* Set the width of the container */
overflow: hidden; /* Hide any overflowing content */
}
.notification-item {
white-space: nowrap; /* Prevent text from wrapping */
animation: scroll 10s linear infinite; /* Apply the animation */
}
@keyframes scroll {
0% {
transform: translateX(100%); /* Start from the right */
}
100% {
transform: translateX(-100%); /* Move to the left */
}
}
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
animations: [] // You can add animations here if needed
})
export class AppComponent {
notifications: string[] = [
"Sync with application X failed with status 500: [error message] - 2023-10-05 08:45",
"Another long notification goes here...",
// Add more notifications as needed
];
}
通过此设置,通知将从右向左平滑滚动。您可以调整动画持续时间(本例中为
10s
)和其他 CSS 属性来微调效果。
请记住根据您的具体要求调整容器的宽度和动画持续时间。此示例提供了一个起点,您可以进一步自定义以满足您的应用程序的需求。