首頁 > web前端 > js教程 > 如何在保持瀏覽器相容性的同時動態變更 HTML5 中的視訊來源?

如何在保持瀏覽器相容性的同時動態變更 HTML5 中的視訊來源?

Mary-Kate Olsen
發布: 2024-11-14 22:48:02
原創
444 人瀏覽過

How to Dynamically Change a Video Source in HTML5 While Maintaining Browser Compatibility?

Dynamically Changing the Video Source in HTML5

In the pursuit of creating a universal video player, it is crucial to consider browser compatibility when dynamically changing the video source.

The Problem

Using multiple tags within a

Solution

To overcome this issue, it is recommended to use a single src attribute within the

Example Implementation

The following JavaScript code demonstrates the process of dynamically changing the video source using the src attribute and canPlayType() function:

var video = document.getElementById('video');
var source = document.createElement('source');
var supported = video.canPlayType('video/mp4');
if (supported == '' || supported == 'no') {
  supported = video.canPlayType('video/webm');
}
if (supported != '' && supported != 'no') {
  source.setAttribute('src', 'path/to/video.' + supported.replace('video/', ''));
  source.setAttribute('type', supported);
  video.appendChild(source);
  video.load();
  video.play();
} else {
  alert('Video file not supported.');
}
登入後複製

This approach simplifies the source-changing process, ensures cross-browser compatibility, and provides a consistent video playback experience.

以上是如何在保持瀏覽器相容性的同時動態變更 HTML5 中的視訊來源?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板