我想在网站上播放视频文件,我有这个简单的 js 代码来做到这一点
var video = document.createElement('video');
video.id = 'myVideo';
video.style.position = 'absolute';
video.style.top = '50%';
video.style.left = '50%';
video.style.transform = 'translate(-50%, -50%) rotate(90deg)'; // Rotate the video 90 degrees
video.style.width = '100vh'; // Use viewport height as width for landscape
video.style.height = '100vw'; // Use viewport width as height for landscape
video.style.objectFit = 'contain'; // Ensure it covers the full area
video.autoplay = true;
video.controls = false; // Hide controls
// Set the source of the video
var source = document.createElement('source');
source.src = './myvideo.mp4'; // Replace with the path to your video
source.type = 'video/mp4';
// Append source to video element
video.appendChild(source);
// Add the video to the screen
document.body.appendChild(video);
video.onloadedmetadata = function() {
console.log('Video metadata loaded successfully');
console.log('Video duration:', video.duration);
};
video.onerror = function() {
console.error('Error loading the video');
};
// Play the video
video.play();
但是在网站上却显示白屏且没有声音。
我不知道我在这里做错了什么,是我没有在我的index.html 文件中包含任何
<video>
标签吗?
此外,我没有收到
video.onloadedmetadata
和 video.onerror
的任何控制台日志
(注意:当我使用 telegra.ph 视频链接作为 source.src 时,它有时会起作用)
当我获取您的代码并添加测试视频时,该代码似乎正在执行您想要的操作。
由于弹出的结果带有另一个视频链接,我的假设是问题出在您正在引用的视频或您用于引用视频的文件路径。
var video = document.createElement('video');
video.id = 'myVideo';
video.style.position = 'absolute';
video.style.top = '50%';
video.style.left = '50%';
video.style.transform = 'translate(-50%, -50%) rotate(90deg)'; // Rotate the video 90 degrees
video.style.width = '100vh'; // Use viewport height as width for landscape
video.style.height = '100vw'; // Use viewport width as height for landscape
video.style.objectFit = 'contain'; // Ensure it covers the full area
video.autoplay = true;
video.controls = false; // Hide controls
// Set the source of the video
var source = document.createElement('source');
source.src = 'https://samplelib.com/lib/preview/mp4/sample-5s.mp4'; // Replace with the path to your video
source.type = 'video/mp4';
// Append source to video element
video.appendChild(source);
// Add the video to the screen
document.body.appendChild(video);
video.onloadedmetadata = function() {
console.log('Video metadata loaded successfully');
console.log('Video duration:', video.duration);
};
video.onerror = function() {
console.error('Error loading the video');
};
// Play the video
video.play();