使用HTML、CSS和JavaScript创建滚动文本

当你已经在建立 Web 应用程序方面有超过 25 年的经验,就像我一样,使用 HTML、CSS 和 JavaScript 已经变得如同呼吸般自然。

在本文中,我将向您展示使用这些工具创建滚动文本的一些简单方法,包括使用纯 HTML、HTML 和CSS以及 HTML + CSS + JS 编码滚动文本的五种不同方法。

1. 纯 HTML 滚动文本

只需在文本周围添加标签即可创建滚动效果。这个标签提供了一些有趣的参数,其中包括:

  • direction — 可以是左、右、上或下
  • scrollamount — 滚动文本的速度
  • loop — 滚动重复的次数

注意:这是一个已弃用的 HTML 标签,因此我建议在现代 Web 项目中谨慎使用它。

2. 使用 CSS 创建动画滚动文本

定义一个名为 scroll 的 CSS 动画,用于动画化 translateX 属性。

CSS

 

Then apply that animation to your text element:
HTML

 

By adding this CSS:
Plain Text

 

Changing from translateX to translateY will give you a vertical scrolling text. Switching 0% and 100% around will give you the reverse scrolling text direction. And in the .scrolling-text CSS class, if you change the 10s duration of the animation, you change the speed of the scrolling text.

3. HTML + CSS + JavaScript 滚动文本

HTML 代码:

HTML

 

CSS 代码:

CSS

 

JavaScript code:
JavaScript

 

This is my most “unelegant” solution for making scrolling text. Basically, it’s cramming text in a container with a scroll and changing the scrolling of the container programmatically. When the scroll amount goes over the container amount, it resets.

4. 使用 jQuery 滚动文本

CSS

 

Use the animate() jQuery function to animate the scrollLeft property, and this will create a scrolling text effect.

在我看来,jQuery 在这种情况下有点过度,只有在您已经在项目中使用了 jQuery 时才有意义。

当然,animate()也可以用于动画化translateXtranslateY属性,就像上面看到的那样。

5. 使用Canvas HTML5滚动文本

这是我最喜欢的方法。特别是因为它非常灵活,提供了很多可能性,比如,例如将滚动文本导出为GIF甚至视频。您可以通过访问PSDDude上的滚动文本生成器,看到其效果,您可以创建自己定制的滚动文本图像和视频。

HTML代码很简单:

HTML

 

And the JS is where the magic happens:
JavaScript

 

Using a loop with requestAnimationFrame() calling the function draw() is actually the way HTML5 games implement their graphics drawing. This is a cool way to create smooth-scrolling text.

使用measureText()上下文方法可以获得文本在屏幕上的大小。这允许通过在到达末尾位置时重置文本位置来创建无缝滚动文本。

奖励:一些滚动文本创意

LED滚动文本GIF

在此链接中了解更多信息。

星球大战开场滚动文本生成器

在此链接中了解更多信息。

股市滚动文本

了解更多 这里.

天气滚动文本

了解更多信息 这里.

这些是通过 滚动文本GIF和视频生成器PSDDude 上创建的。

结论

现在你知道如何使用HTML、CSS和/或 JavaScript 制作滚动文本。

你将如何使用这个?给我留言让我知道。如果你觉得我遗漏了一个重要的滚动文本创建方法,请告诉我你的想法。

Source:
https://dzone.com/articles/scrolling-text-html-css-javascript