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

เลือกอิลิเมนต์ที่ alt มีคำว่า Tutorials ด้วย CSS

ใช้ Selector [attribute~="value"] เพื่อเลือกอิลิเมนต์ที่ค่าแอตทริบิวต์มีคำที่ระบุอยู่ (คั่นด้วย space)

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

ลองรันโค้ดด้านล่างเพื่อทดสอบ [attribute~="value"] selector โดยค้นหาคำว่า Tutorials:

<!DOCTYPE html>
<html>
<head>
  <style>
    [alt~="Tutorials"] {
      border: 5px solid orange;
      border-radius: 5px;
    }
  </style>
</head>
<body>
  <img src="https://www.tutorialspoint.com/videotutorials/images/tutor_connect_home.jpg" height="200" width="200" alt="Tutor Connect">
  <img src="https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg" height="200" width="200" alt="Tutorials Library">
</body>
</html>

ผลลัพธ์: รูปที่สองมีขอบสีส้ม เพราะ alt="Tutorials Library" มีคำว่า "Tutorials" อยู่ (คั่นด้วย space) รูปแรก alt="Tutor Connect" ไม่มีคำว่า "Tutorials" ตรงๆ (มีแค่ "Tutor") จึงไม่ตรง ต่างจาก *= ที่หา substring