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

วิธาฝังวิดีโอด้วยโค้ด HTML (YouTube Embed)


บทนำ

ใช้แท็ก <iframe> สำหรับฝังวิดีโอจาก YouTube, Vimeo, หรือแพลตฟอร์มอื่นๆ ตั้งค่า width height และ src เป็น Embed URL

ขั้นตอนดึง Embed Link จาก YouTube

  1. เปิดวิดีโอ YouTube
  2. กดปุ่ม Share (แชร์)
  3. เลือก Embed (ฝัง)
  4. คัดลอก URL ใน src="https://www.youtube.com/embed/VIDEO_ID"

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

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Video Embed</title>
  </head>
  <body>
    <p>Learn Eclipse</p>
    <br />
    <iframe width="560" height="315" 
            src="https://www.youtube.com/embed/VIDEO_ID" 
            frameborder="0" 
            allowfullscreen
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture">
    </iframe>
  </body>
</html>

แอตทริบิวต์ iframe สำคัญ

แอตทริบิวต์คำอธิบาย
width / heightขนาด Player (Pixel หรือ %)
srcEmbed URL
frameborderขอบ (0 = ไม่มี, 1 = มี) - Deprecated ใช้ CSS แทน
allowfullscreenอนุญาตเต็มจอ
allowFeature Policy (autoplay, clipboard, encrypted-media, etc.)
loading="lazy"โหลดล่าช้า (Performance)
referrerpolicyReferrer Policy

Responsive Embed (CSS)

.video-container {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; /* 16:9 Aspect Ratio */
  height: 0;
}
.video-container iframe {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
}

YouTube Parameters

  • ?autoplay=1 - เล่นอัตโนมัติ (ต้องมี mute)
  • ?mute=1 - ปิดเสียง
  • ?controls=0 - ซ่อน Controls
  • ?rel=0 - ไม่แสดงวิดีโอแนะนำตอนจบ
  • ?start=30 - เริ่มที่ 30 วินาที