使用 HTML、CSS 和 JavaScript 創建滾動文本

當您已經建立網絡應用程式超過25年,就像我所做的那樣,使用HTML、CSS和JavaScript已經變得如同呼吸一般自然。

在本文中,我將展示一些使用這些工具創建滾動文本的簡單方法,包括使用純HTML、HTML和CSS以及HTML + CSS + JS編碼滾動文本的五種不同方法。

1. 純HTML滾動文本

只需在文本周圍添加一個標籤即可創建滾動效果。此標籤提供一些有趣的參數,其中包括:

  • direction — 可以是左、右、上或下
  • scrollamount — 滾動文本的速度
  • loop — 滾動應重複多少次

注意:這是一個不建議使用的HTML標籤,因此我建議在現代網絡項目中使用時要謹慎。

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. 使用 HTML5 Canvas 滾動文本

這是我最喜歡的方法。特別是因為它非常靈活,提供了許多可能性,例如,將滾動文本導出為 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