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

Event ใดเกิดเมื่อ Paste เนื้อหาใน Element ใน JavaScript?

Event onpaste ทริกเกอร์เมื่อ User Paste เนื้อหา ลงใน Element (Input, Textarea, ContentEditable)

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

<!DOCTYPE html>
<html>
  <body>
    <input type="text" onpaste="pasteFunction()" value="paste text here">
    <script>
      function pasteFunction() {
        document.write("Text pasted successfully!");
      }
    </script>
  </body>
</html>

คำอธิบาย

  • ทริกเกอร์: Ctrl+V, Cmd+V, Right-click → Paste, Menu → Paste
  • เข้าถึงข้อมูล Paste: event.clipboardData.getData('text/plain')
  • สามารถ event.preventDefault() เพื่อ Block/Modify Paste

ClipboardData API (Modern)

const input = document.querySelector('input');
input.addEventListener('paste', (e) => {
  // อ่านข้อมูลจาก Clipboard
  const text = e.clipboardData.getData('text/plain');
  console.log('Pasted:', text);
  
  // Block Paste
  // e.preventDefault();
  
  // Modify Paste (Uppercase)
  // e.preventDefault();
  // input.value += text.toUpperCase();
});

Clipboard Events ทั้งหมด

Eventทริกเกอร์เมื่อClipboardData Access
copyUser Copy (Ctrl+C)Write Only (setData)
cutUser Cut (Ctrl+X)Write Only
pasteUser Paste (Ctrl+V)Read Only (getData)

Async Clipboard API (สมัยใหม่)

// Read Clipboard (ต้อง Permission)
async function readClipboard() {
  try {
    const text = await navigator.clipboard.readText();
    console.log(text);
  } catch (err) {
    console.error('Clipboard read failed:', err);
  }
}

// Write Clipboard
await navigator.clipboard.writeText('Hello World');

Security: Clipboard API ต้อง HTTPS และ User Gesture (Click) ในบาง Browser