Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีทำ Simple Looping Background Color Animation ด้วย CSS

เรียนรู้ทำ simple animated background color loop ด้วย pure CSS ใช้ keyframes และ CSS animation properties ต่างๆ

ตัวอย่าง target HTML <body> element โดยตรง แตะ apply ให้ HTML element, class, หรือ id ใดๆ ก็ได้

วิธีทำ Simple Looping Background Color Animation ด้วย CSS

The Code

ใช้ demo นี้เป็น reference

หมายเหตุ: code นี้ไม่ทำงานใน IE9

วางแผน Animation

แม้ไม่รู้ผลลัพธ์สุดท้าย ควรมีไอเดียทิศทาง กำหนดเรื่อง looping animation ก่อนเขียนโค้ด:

  • อยากใช้ background colors กี่สี?
  • Total animation duration นานแค่ไหน?
  • Animation curve type ไหน?

เพื่อความเรียบง่าย ใช้:

  • 5 background colors ต่างกัน
  • Duration 10 วินาที (แต่ละสีแสดง 2 วินาที)
  • Linear animation curve (ความเร็วคงที่ ตั้งแต่ต้นจนจบ)

ใช้ Coolers.co สร้าง color palette harmonious:

วิธีทำ Simple Looping Background Color Animation ด้วย CSS

Hex colors สำหรับ background animation loop:

  • Sunset orange: #EE6055
  • Medium aquamarine: #60D394
  • Pale green: #AAF683
  • Mellow yellow: #FFD97D
  • Vivid tangerine: #FF9B85

จำชื่อสีไม่ได้ (มาจาก Coolers) ใส่ไว้แค่ reference

มี 5 สี จะนำเข้า looping animation แสดงแต่ละสี 2 วินาที

สร้าง Looping CSS Animation

CSS animations keyframes ทำงานเป็น percentages 0% ถึง 100% เพิ่ม CSS keyframes นี้ใน stylesheet:

/* Standard syntax */ @keyframes backgroundColorPalette { 0% { background: #ee6055; } 25% { background: #60d394; } 50% { background: #aaf683; } 75% { background: #ffd97d; } 100% { background: #ff9b85; } }

ตอนนี้มี keyframes property ชื่อ backgroundColorPalette 5 color intervals แบ่งเท่าๆ กัน 0% ถึง 100%

สร้าง body element CSS rule-set ใช้ keyframes color palette:

body { animation-name: backgroundColorPalette; animation-duration: 10s; animation-iteration-count: infinite; animation-direction: alternate; }

ถ้าทำถูกต้อง จะได้ background color animation รันต่อเนื่อง transition สีสลับกัน 2 วินาที/สี

The Code

ใช้ demo นี้เป็น reference

CSS ทำงานอย่างไร

  • animation-name = backgroundColorPalette assign keyframes ให้ body element
  • animation-duration: 10s total duration 10 วินาที (ใช้ milliseconds 10000 ได้)
  • animation-iteration-count: infinite ทำให้ loop ตลอดเวลา Default CSS คือ 1 animation cycle
  • animation-direction: alternate เล่นจากต้นถึงปลาย แล้วปลายถึงต้น กัน ugly jump ที่เกิดจาก normal direction value

ข้อมูลเพิ่มเติม

Default CSS animation speed curve type = linear ไม่ต้อง declare property ใน rule-sets ตอนอยากใช้ linear

แต่อาจอยากเพิ่ม animation-timing-function: linear; ให้ code expressive มากขึ้น — โดยเฉพาะทำงานทีม ยากที่จะจำ default property values ทั้งหมดใน CSS