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

การสร้างแอนิเมชันสำหรับคุณสมบัติ CSS opacity

คุณสมบัติ opacity เป็นหนึ่งในคุณสมบัติที่เหมาะสมที่สุดสำหรับการสร้างแอนิเมชัน เพราะได้รับการ GPU acceleration และไม่ทำให้เกิด layout reflow

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
<head>
  <style>
    #demo1 {
      position: absolute;
      top: 60px;
      width: 300px;
      height: 150px;
      background-color: lightblue;
      animation: myanim 4s infinite;
    }
    #demo2 {
      position: absolute;
      top: 90px;
      left: 30px;
      width: 300px;
      height: 150px;
      background-color: orange;
      animation: myanim 3s infinite;
    }
    #demo3 {
      position: absolute;
      top: 120px;
      left: 60px;
      width: 350px;
      height: 150px;
      background-color: coral;
    }
    @keyframes myanim {
      30% {
        opacity: 0.4;
      }
    }
  </style>
</head>
<body>
  <p>Showing opacity</p>
  <div id="demo1"><h1>End div</h1></div>
  <div id="demo2"></div>
  <div id="demo3"><h1>Start div</h1></div>
</body>
</html>

คำอธิบาย: กล่อง 3 กล่องทับซ้อนกัน ทุก 30% ของแอนิเมชัน จะมีความทึบแสงลดลงเหลือ 0.4 (โปร่งใส 60%) แล้วกลับมาทึบเต็มที่ (1) ทำให้เห็นเอฟเฟกต์ fade in/out

ข้อดีของการ animate opacity:

  • GPU accelerated (cheap)
  • ไม่ทำให้เกิด reflow/repaint ของ element อื่น
  • สามารถรวมกับ transform ได้อย่างมีประสิทธิภาพ

เคล็ดลับ: หากต้องการซ่อน element เลย ใช้ opacity: 0 ร่วมกับ pointer-events: none และ visibility: hidden (หลัง transition จบ) เพื่อไม่ให้ขวางการคลิก