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

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

ตัวอย่างการสร้างแอนิเมชันเลื่อน element แนวตั้งด้วยคุณสมบัติ top (ต้องใช้ร่วมกับ position: absolute/relative/fixed)

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

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      position: absolute;
      width: 300px;
      height: 200px;
      background-color: orange;
      color: white;
      top: 0;
      animation: myanim 3s infinite;
    }
    @keyframes myanim {
      30% {
        top: 300px;
      }
    }
  </style>
</head>
<body>
  <h1>CSS top property</h1>
  <div>
    <h1>This is demo text!</h1>
  </div>
</body>
</html>

คำอธิบาย: กล่องเริ่มต้นชิดบน (top: 0) ที่ 30% จะเลื่อนลง 300px แล้วกลับขึ้นมา

ข้อควรระวัง: การ animate top ก่อให้เกิด layout reflow ไม่ได้รับ GPU acceleration

แนวทางที่ดีกว่า: ใช้ transform: translateY(300px) แทน

div {
  position: absolute;
  top: 0;
  animation: slide 3s infinite;
}
@keyframes slide {
  30% { transform: translateY(300px); }
}