阿里云主机折上折
  • 微信号
Current Site:Index > The usage and attributes of the '<video>' tag

The usage and attributes of the '<video>' tag

Author:Chuan Chen 阅读数:42892人阅读 分类: HTML

Basic Concepts of the <video> Tag

The <video> tag is an HTML5 addition for embedding video content in web pages, allowing developers to play videos directly without the need for third-party plugins. Compared to traditional technologies like Flash, the <video> tag offers better performance, lower resource consumption, and higher compatibility.

<video src="example.mp4"></video>

This simplest example demonstrates how to embed a video file using the <video> tag. Modern browsers automatically provide a basic control interface for the video, including play/pause buttons, a progress bar, and volume controls.

Core Attributes Explained

src Attribute

The src attribute specifies the URL of the video file to be played, which can be a relative or absolute path. While this is the most straightforward way to specify a video source, using the <source> child element is more recommended in actual development.

<video src="assets/videos/intro.mp4"></video>

controls Attribute

controls is a Boolean attribute. When added, the browser displays the default video control interface. If this attribute is not set, the video will not show any control buttons, and playback must be controlled via JavaScript.

<video src="movie.mp4" controls></video>

autoplay Attribute

The autoplay attribute causes the video to start playing automatically when ready. However, note that most modern browsers block autoplay with sound unless the video is muted or the user has already interacted with the website.

<video src="advertisement.mp4" autoplay muted></video>

loop Attribute

The loop attribute makes the video restart automatically after it ends, suitable for background videos or looping content.

<video src="background-loop.mp4" loop muted autoplay></video>

muted Attribute

The muted attribute sets the video to be muted by default, which is particularly useful in autoplay scenarios, as most browsers allow muted videos to autoplay.

<video src="presentation.mp4" autoplay muted></video>

poster Attribute

The poster attribute specifies an image to display while the video is downloading or before the user clicks play. If not set, the browser typically shows the first frame of the video as a preview.

<video src="tutorial.mp4" poster="preview.jpg" controls></video>

preload Attribute

The preload attribute tells the browser how to load the video resource, with three possible values:

  • auto: The browser should load the entire video.
  • metadata: Only load the video's metadata (e.g., duration, dimensions).
  • none: Do not preload the video.
<video src="long-video.mp4" preload="metadata"></video>

width and height Attributes

These attributes set the width and height of the video display area in pixels. If not set, the video area adjusts automatically based on the video's original dimensions.

<video src="presentation.mp4" width="640" height="360" controls></video>

Multiple Source Files and Format Compatibility

Since different browsers support different video formats, it is often necessary to provide multiple video sources. In this case, the <source> element can be used instead of the src attribute, and the browser will attempt to load the first supported format in order.

<video controls>
  <source src="movie.webm" type="video/webm">
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

The type attribute helps the browser determine whether it can play the format, avoiding downloads of unsupported formats. Common video MIME types include:

  • video/mp4: MP4 format (H.264 encoding).
  • video/webm: WebM format (VP8/VP9 encoding).
  • video/ogg: Ogg format (Theora encoding).

Responsive Video Design

To ensure videos display well on screens of different sizes, CSS can be used to implement responsive design. The most common method is to set max-width: 100% and height: auto.

<style>
  .responsive-video {
    max-width: 100%;
    height: auto;
  }
</style>

<video class="responsive-video" controls>
  <source src="demo.mp4" type="video/mp4">
</video>

For maintaining a specific aspect ratio in responsive videos, the padding trick can be used:

<style>
  .video-container {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 aspect ratio */
    height: 0;
    overflow: hidden;
  }
  
  .video-container video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>

<div class="video-container">
  <video controls>
    <source src="demo.mp4" type="video/mp4">
  </video>
</div>

JavaScript Control API

The <video> element provides a rich JavaScript API, allowing developers to create custom video control interfaces or implement special features.

Basic Control Methods

const myVideo = document.getElementById("myVideo");

// Play the video
myVideo.play();

// Pause the video
myVideo.pause();

// Toggle play/pause
function togglePlay() {
  if (myVideo.paused) {
    myVideo.play();
  } else {
    myVideo.pause();
  }
}

// Jump to a specific time point (in seconds)
myVideo.currentTime = 30; // Jump to 30 seconds

// Adjust volume (0.0 to 1.0)
myVideo.volume = 0.5; // Set to 50% volume

// Mute/unmute
myVideo.muted = true; // Mute

Common Properties

// Video duration (seconds)
const duration = myVideo.duration;

// Current playback position (seconds)
const currentTime = myVideo.currentTime;

// Playback status
const isPaused = myVideo.paused;
const isEnded = myVideo.ended;

// Volume-related
const volumeLevel = myVideo.volume;
const isMuted = myVideo.muted;

// Video dimensions
const videoWidth = myVideo.videoWidth;
const videoHeight = myVideo.videoHeight;

Important Events

myVideo.addEventListener("play", function() {
  console.log("Video started playing");
});

myVideo.addEventListener("pause", function() {
  console.log("Video paused");
});

myVideo.addEventListener("ended", function() {
  console.log("Video playback ended");
});

myVideo.addEventListener("timeupdate", function() {
  console.log("Current playback position: " + myVideo.currentTime);
  // Custom progress bar can be updated here
});

myVideo.addEventListener("volumechange", function() {
  console.log("Volume changed: " + myVideo.volume);
});

myVideo.addEventListener("loadedmetadata", function() {
  console.log("Video metadata loaded");
  console.log("Video duration: " + myVideo.duration + " seconds");
});

myVideo.addEventListener("error", function() {
  console.error("Video loading error");
});

Advanced Features and Techniques

Custom Control Interface

By hiding the default control interface (using the controls attribute) and using the JavaScript API, a fully custom video player can be created.

<video id="customVideo">
  <source src="movie.mp4" type="video/mp4">
</video>

<div class="custom-controls">
  <button id="playBtn">Play</button>
  <input type="range" id="progressBar" min="0" max="100" value="0">
  <button id="muteBtn">Mute</button>
  <input type="range" id="volumeSlider" min="0" max="100" value="100">
</div>

<script>
  const video = document.getElementById("customVideo");
  const playBtn = document.getElementById("playBtn");
  const progressBar = document.getElementById("progressBar");
  const muteBtn = document.getElementById("muteBtn");
  const volumeSlider = document.getElementById("volumeSlider");

  playBtn.addEventListener("click", function() {
    if (video.paused) {
      video.play();
      playBtn.textContent = "Pause";
    } else {
      video.pause();
      playBtn.textContent = "Play";
    }
  });

  video.addEventListener("timeupdate", function() {
    const progress = (video.currentTime / video.duration) * 100;
    progressBar.value = progress;
  });

  progressBar.addEventListener("input", function() {
    const seekTime = (progressBar.value / 100) * video.duration;
    video.currentTime = seekTime;
  });

  muteBtn.addEventListener("click", function() {
    video.muted = !video.muted;
    muteBtn.textContent = video.muted ? "Unmute" : "Mute";
  });

  volumeSlider.addEventListener("input", function() {
    video.volume = volumeSlider.value / 100;
  });
</script>

Picture-in-Picture Mode

Modern browsers support Picture-in-Picture (PiP) mode, allowing videos to float above other windows.

const pipButton = document.getElementById("pipButton");

pipButton.addEventListener("click", async function() {
  try {
    if (video !== document.pictureInPictureElement) {
      await video.requestPictureInPicture();
    } else {
      await document.exitPictureInPicture();
    }
  } catch (error) {
    console.error("PiP error:", error);
  }
});

video.addEventListener("enterpictureinpicture", function() {
  console.log("Entered PiP mode");
});

video.addEventListener("leavepictureinpicture", function() {
  console.log("Exited PiP mode");
});

Subtitles and Tracks

The <video> tag supports adding subtitles or chapter information via the <track> element.

<video controls>
  <source src="movie.mp4" type="video/mp4">
  <track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="English">
  <track src="subtitles_zh.vtt" kind="subtitles" srclang="zh" label="Chinese" default>
</video>

Example WebVTT subtitle file (subtitles_en.vtt):

WEBVTT

1
00:00:01.000 --> 00:00:04.000
Hello, welcome to this video tutorial.

2
00:00:05.000 --> 00:00:08.000
Today we'll learn about HTML5 video element.

Media Fragments

Specific parts of a video can be played by adding media fragment identifiers to the URL.

<video controls>
  <source src="movie.mp4#t=10,20" type="video/mp4">
</video>
<!-- Plays the portion from 10 to 20 seconds -->

<video controls>
  <source src="movie.mp4#t=30" type="video/mp4">
</video>
<!-- Starts playing from 30 seconds -->

Performance Optimization and Best Practices

Lazy Loading

For videos further down the page, the loading="lazy" attribute can be used to lazy-load them, improving initial page load speed.

<video controls loading="lazy" poster="preview.jpg">
  <source src="long-video.mp4" type="video/mp4">
</video>

Preloading Keyframes

For long videos, preloading keyframes (metadata) instead of the entire video can reduce initial bandwidth usage.

<video preload="metadata" controls>
  <source src="presentation.mp4" type="video/mp4">
</video>

Adaptive Bitrate Streaming

For high-quality video content, consider using adaptive bitrate streaming (e.g., HLS or DASH) instead of a single video file.

<!-- Using the hls.js library to play HLS streams -->
<video id="hlsVideo" controls></video>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
  if (Hls.isSupported()) {
    const video = document.getElementById("hlsVideo");
    const hls = new Hls();
    hls.loadSource("stream.m3u8");
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, function() {
      video.play();
    });
  }
</script>

Video Format Selection

Choose the best video format combination based on the target audience:

  • Modern browsers: Prioritize WebM (VP9) + MP4 (H.264) combination.
  • Older device compatibility: MP4 (H.264) + Ogg (Theora).
  • High-quality needs: Consider AV1 encoding (browser support is increasing).
<video controls>
  <source src="movie.av1.mp4" type="video/mp4; codecs=av01.0.05M.08">
  <source src="movie.vp9.webm" type="video/webm; codecs=vp9">
  <source src="movie.h264.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Accessibility

Ensure video content is accessible to all users:

Provide Subtitles and Transcripts

<video controls>
  <source src="lecture.mp4" type="video/mp4">
  <track src="subtitles.vtt" kind="subtitles" srclang="zh" label="Chinese subtitles" default>
  <track src="description.vtt" kind="descriptions" srclang="zh">
</video>

<div id="transcript">
  <h3>Video Transcript</h3>
  <p>Full text content of the video...</p>
</div>

Keyboard Operability

Ensure custom video controls can be operated via keyboard:

// Add keyboard events for custom controls
playBtn.addEventListener("keydown", function(e) {
  if (e.key === "Enter" || e.key === " ") {
    e.preventDefault();
    togglePlay();
  }
});

progressBar.addEventListener("keydown", function(e) {
  if (e.key === "ArrowLeft") {
    video.currentTime = Math.max(0, video.currentTime - 5);
  } else if (e.key === "ArrowRight") {
    video.currentTime = Math.min(video.duration, video.currentTime + 5);
  }
});

ARIA Attributes

Add appropriate ARIA attributes to custom players:

<div class="custom-player" role="application" aria-label="Video player">
  <video id="videoPlayer" aria-labelledby="videoTitle"></video>
  <h2 id="videoTitle">HTML5 Video Tutorial</h2>
  <div class="controls">
    <button id="playButton" aria-label="Play/Pause"></button>
    <div id="progress" role="slider" aria-valuemin="0" aria-valuemax="100"></div>
  </div>
</div>

Cross-Browser Compatibility Handling

While modern browsers have good support for <video>, there are still some differences to note:

Detecting Format Support

function canPlayType(type) {
  const video = document.createElement("video");
  return !!video.canPlayType(type);
}

const supportsMP4 = canPlayType("video/mp4");
const supportsWebM = canPlayType("video/webm");
const supportsOgg = canPlayType("video/ogg");

console.log(`MP4 support: ${supportsMP4}`);
console.log(`WebM support: ${supportsWebM}`);
console.log(`Ogg support: ${supportsOgg}`);

Fallback Solutions

For older browsers that do not support HTML5 video at all (e.g., IE8 and below), provide a Flash fallback or direct download link.

<video controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.webm" type="video/webm">
  <!-- Flash fallback -->
  <object type="application/x-shockwave-flash" data="player.swf">
    <param name="movie" value="player.swf">
    <param name="flashvars" value="video=movie.mp4">
    <!-- Final fallback: download link -->
    <a href="movie.mp4">Download video</a>
  </object>
</video>

Browser-Specific Handling

Some browsers may require special handling, such as inline playback restrictions on iOS:

// Detect iOS devices
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

if (isIOS) {
  // iOS requires user interaction to play videos
  document.addEventListener("click", function firstPlay() {
    video.play().catch(e => console.error(e));
    document.removeEventListener("click", firstPlay);
  }, { once: true });
}

Security and Privacy Considerations

Cross-Origin Restrictions

If video resources come from a different domain, CORS headers may need to be set:

<video controls crossorigin="anonymous">
  <source src="https://another-domain.com/video.mp4" type="video/mp4">
</video>

The server needs to set the response header:

Access-Control-Allow-Origin: *

Preventing Hotlinking

Protect videos from being directly linked by other websites:

// Check if document.referrer is from an allowed domain
if (document.referrer && !document.referrer.includes("yourdomain.com")) {
  video.src = "blocked.mp4"; // Display a "hotlinking prohibited" video
}

Encrypted Media Extensions (EME)

For video content requiring DRM protection, Encrypted Media Extensions can be used:

const video = document.querySelector("video");
const config = [{
  initDataTypes: ["cenc"],
  videoCapabilities: [{
    contentType: 'video/mp4;codecs="avc1.42E01E"'
  }]
}];

navigator.requestMediaKeySystemAccess("com.widevine.alpha", config)
  .then(function(keySystemAccess) {
    return keySystemAccess.createMediaKeys();
  })
  .then(function(mediaKeys) {
    video.setMediaKeys(mediaKeys);
    video.src = "protected-video.mp4";
  });

Practical Application Examples

Video Background

Create a full-screen video background effect:

<style>
  .video-background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
    object-fit:

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.