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

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

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

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

<!DOCTYPE html>
<html>
<head>
  <style>
    #demo {
      position: absolute;
      right: 0;
      width: 300px;
      height: 200px;
      background-color: blue;
      animation: myanim 5s infinite;
    }
    @keyframes myanim {
      30% {
        right: 350px;
      }
    }
  </style>
</head>
<body>
  <h1>CSS right property</h1>
  <div id="demo">
    <h1>This is demo text.</h1>
  </div>
</body>
</html>

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

ข้อควรระวัง: การ animate right (เช่นเดียวกับ left/top/bottom) ก่อให้เกิด layout reflow และไม่ได้รับ GPU acceleration

แนวทางที่ดีกว่า: ใช้ transform: translateX(-350px) แทน (ค่าลบเพราะเลื่อนซ้าย)

#demo {
  position: absolute;
  right: 0;
  animation: slide 5s infinite;
}
@keyframes slide {
  30% { transform: translateX(-350px); }
}