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

วิธีลบขอบ (Border) ขององค์ประกอบที่แก้ไขได้ (Contenteditable) ด้วย CSS

ซ่อน Outline ของ Contenteditable Element

เบราว์เซอร์จะแสดง outline (ขอบประกาย) รอบองค์ประกอบที่มี contenteditable="true" เมื่อ focus ใช้ outline: none หรือ outline: 0px solid transparent เพื่อซ่อน

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

<!DOCTYPE html>
<html>
<head>
  <style>
    body{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
    p{ font-size: 40px; }
    [contenteditable] { outline: 0px solid transparent; }
  </style>
</head>
<body>
  <h1>ตัวอย่างลบ Border Contenteditable</h1>
  <p contenteditable="true">ย่อหน้านี้แก้ไขได้ ลองคลิกดู</p>
</body>
</html>

ข้อควรระวังด้าน Accessibility

Outline เป็นสัญญาณสำคัญสำหรับ Keyboard Navigation – ผู้ใช้แป้นพิมพ์ต้องมองเห็นว่าองค์ประกอบไหนอยู่ใน focus หากลบ outline ต้องใส่ focus style แทน:

[contenteditable]:focus {
  outline: none;
  box-shadow: 0 0 0 2px #445deb; /* focus ring แทน */
  background-color: #f0f4ff; /* หรือเปลี่ยนพื้นหลัง */
}

โหมดแก้ไขขั้นสูง

  • contenteditable="plaintext-only" – รับแค่ plain text (ไม่รับ HTML tags)
  • contenteditable="true" – รับ HTML (default)
  • ใช้ document.execCommand() (deprecated) หรือ ContentEditable API ใหม่สำหรับ toolbar formatting