html 使用video.play()时,视频显示白色屏幕

uz75evzq  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(179)

我想在一个网站上播放一个视频文件,我有这个功能,通过它我试图做到这一点

function closePageWithCountdown(seconds) {
  const countdownElement = document.createElement("countdowntime");
  countdownElement.style.position = "fixed";
  countdownElement.style.top = "0";
  countdownElement.style.left = "0";
  countdownElement.style.backgroundColor = "red";
  countdownElement.style.color = "white";
  countdownElement.style.padding = "5px";

  document.body.appendChild(countdownElement);

  function updateCountdown() {
    countdownElement.textContent = `Page will automatically close in ${seconds} seconds`;

    if (seconds === 0) {
      document.body.removeChild(countdownElement);
      document.getElementsByTagName('html')[0].remove();
      document.write('Resource Exhausted !\n<br>You may reload the page or close the tab.');
      var centeredText = document.createElement("div");
      centeredText.innerHTML = "Some Text Here";
      centeredText.style.position = "fixed";
      centeredText.style.bottom = "0";
      centeredText.style.left = "0";
      centeredText.style.right = "0";
      centeredText.style.textAlign = "center";
      // centeredText.style.backgroundColor = "rgba(255, 255, 255, 0.8";
      centeredText.style.padding = "10px";
      centeredText.style.zIndex = "999"; // Ensures it appears on top of other content
      
      // Append the element to the body
      document.body.appendChild(centeredText);

      document.getElementsByTagName('html')[0].style.overflow = 'hidden';
      document.getElementsByTagName('body')[0].style.overflow = 'hidden';
      
      var colors = ['red', 'blue', 'green']; // List of rainbow colors
      var colorIndex = 0; // Initialize color index

      function flash() {
            centeredText.style.color = colors[colorIndex];
            colorIndex = (colorIndex + 1) % colors.length; // Cycle through colors
      }

      var clr = setInterval(flash, 500);
      
      // Create a new div element to hold the text
      var flashbackText = document.createElement('div');
      flashbackText.innerHTML = 'Click here to watch';
      flashbackText.style.position = 'absolute';
      flashbackText.style.top = '50%';
      flashbackText.style.left = '50%';
      flashbackText.style.transform = 'translate(-50%, -50%)';
      flashbackText.style.fontSize = '1.5em';
      flashbackText.style.fontWeight = 'bold';
      flashbackText.style.backgroundColor = 'yellow';
      flashbackText.style.padding = '10px';
      flashbackText.style.cursor = 'pointer';
      flashbackText.style.zIndex = '1000'; // Ensure it's above other elements

      // Append the text to the body
      document.body.appendChild(flashbackText);
    
      // Event listener for the click event
      flashbackText.addEventListener('click', function() {
       // Clear the screen
       document.body.innerHTML = '';

       // Create a video element
       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();

       // Event listener for when the video ends
       video.addEventListener('ended', function() {
        // Clear the video and show the original text again
        document.body.innerHTML = '';
        document.body.appendChild(flashbackText);
        document.body.appendChild(centeredText);
        document.write('Resource Exhausted !\n<br>You may reload the page or close the tab.');
       });    
      });
           

    } else {
      seconds--;
      setTimeout(updateCountdown, 1000);
    }
  }

  updateCountdown();
}
closePageWithCountdown(1) // 1 sec for testing

字符串

预期行为:有一个突出显示的文本(在屏幕中心),如果用户点击它,它会播放视频,当视频结束时,它会返回到页面的旧内容。

然而,在网站上它显示一个白色屏幕,没有声音。
我不知道我在这里做错了什么,是不是我没有在我的index.html文件中包含任何<video>标记?
此外,我没有获得video.onloadedmetadatavideo.onerror的任何控制台日志
(Note:当我使用telegra.ph视频链接作为源时,它有时会工作。

tyg4sfes

tyg4sfes1#

source是一个undefined变量,试图引用它会导致脚本崩溃。你需要设置video的属性,当然你只需要将video添加到HTML中。在计数器的末尾,你会显示资源已经耗尽,这是不正确的,因为资源工作正常。您不需要删除HTML的第一个子元素,也不需要在计数器完成其工作时添加该文本。您只需要在视频结束时执行此操作。请参阅下面的片段:

function closePageWithCountdown(seconds) {
  const countdownElement = document.createElement("countdowntime");
  countdownElement.style.position = "fixed";
  countdownElement.style.top = "0";
  countdownElement.style.left = "0";
  countdownElement.style.backgroundColor = "red";
  countdownElement.style.color = "white";
  countdownElement.style.padding = "5px";

  document.body.appendChild(countdownElement);

  function updateCountdown() {
    countdownElement.textContent = `Page will automatically close in ${seconds} seconds`;

    if (seconds === 0) {
      document.body.removeChild(countdownElement);
      //document.getElementsByTagName('html')[0].remove();
      //document.write('Resource Exhaustedd !\n<br>You may reload the page or close the tab.');
      var centeredText = document.createElement("div");
      centeredText.innerHTML = "Some Text Here";
      centeredText.style.position = "fixed";
      centeredText.style.bottom = "0";
      centeredText.style.left = "0";
      centeredText.style.right = "0";
      centeredText.style.textAlign = "center";
      // centeredText.style.backgroundColor = "rgba(255, 255, 255, 0.8";
      centeredText.style.padding = "10px";
      centeredText.style.zIndex = "999"; // Ensures it appears on top of other content
      
      // Append the element to the body
      document.body.appendChild(centeredText);

      document.getElementsByTagName('html')[0].style.overflow = 'hidden';
      document.getElementsByTagName('body')[0].style.overflow = 'hidden';
      
      var colors = ['red', 'blue', 'green']; // List of rainbow colors
      var colorIndex = 0; // Initialize color index

      function flash() {
            centeredText.style.color = colors[colorIndex];
            colorIndex = (colorIndex + 1) % colors.length; // Cycle through colors
      }

      var clr = setInterval(flash, 500);
      
      // Create a new div element to hold the text
      var flashbackText = document.createElement('div');
      flashbackText.innerHTML = 'Click here to watch';
      flashbackText.style.position = 'absolute';
      flashbackText.style.top = '50%';
      flashbackText.style.left = '50%';
      flashbackText.style.transform = 'translate(-50%, -50%)';
      flashbackText.style.fontSize = '1.5em';
      flashbackText.style.fontWeight = 'bold';
      flashbackText.style.backgroundColor = 'yellow';
      flashbackText.style.padding = '10px';
      flashbackText.style.cursor = 'pointer';
      flashbackText.style.zIndex = '1000'; // Ensure it's above other elements

      // Append the text to the body
      document.body.appendChild(flashbackText);
    
      // Event listener for the click event
      flashbackText.addEventListener('click', function() {
       // Clear the screen
       document.body.innerHTML = '';

       // Create a video element
       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
       video.src = 'https://telegra.ph/file/9d80fe1d60b2896d8b47b.mp4'; // Replace with the path to your video
       video.type = 'video/mp4';
       //source.type = 'video/mp4';

       // Append source to video element
       //document..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();

       // Event listener for when the video ends
       video.addEventListener('ended', function() {
        // Clear the video and show the original text again
        document.body.innerHTML = '';
        document.body.appendChild(flashbackText);
        document.body.appendChild(centeredText);
        document.write('Resource Exhausted !\n<br>You may reload the page or close the tab.');
       });    
      });
           

    } else {
      seconds--;
      setTimeout(updateCountdown, 1000);
    }
  }

  updateCountdown();
}
closePageWithCountdown(1) // 1 sec for testing

个字符

kxeu7u2r

kxeu7u2r2#

当我获取您的代码并添加测试视频时,代码似乎正在执行您的意图。
由于结果会弹出另一个视频链接,我的假设是问题出在你引用的视频或你用来引用视频的文件路径上。

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();

字符串

py49o6xq

py49o6xq3#

当您将document.body.innerHTML设置为空字符串时,您实际上删除了所有现有元素,包括触发视频播放的脚本。这可能会导致意外行为。
与其清除整个document.body,不如考虑创建一个容器元素来同时保存视频和原始文本。然后,您可以将该容器的内容替换为视频,并在需要时恢复为原始文本。下面是代码的修改版本来说明这一点

function closePageWithCountdown(seconds) {
  const countdownElement = document.createElement("countdowntime");
  countdownElement.style.position = "fixed";
  countdownElement.style.top = "0";
  countdownElement.style.left = "0";
  countdownElement.style.backgroundColor = "red";
  countdownElement.style.color = "white";
  countdownElement.style.padding = "5px";

  document.body.appendChild(countdownElement);

  function updateCountdown() {
    countdownElement.textContent = `Page will automatically close in ${seconds} seconds`;

    if (seconds === 0) {
      document.body.removeChild(countdownElement);

      // Create a container to hold the video and original text
      var container = document.createElement('div');
      container.style.position = 'absolute';
      container.style.top = '0';
      container.style.left = '0';
      container.style.width = '100%';
      container.style.height = '100%';
      container.style.overflow = 'hidden';
      document.body.appendChild(container);

      // Original text
      var centeredText = document.createElement("div");
      centeredText.innerHTML = "Some Text Here";
      centeredText.style.position = "fixed";
      centeredText.style.bottom = "0";
      centeredText.style.left = "0";
      centeredText.style.right = "0";
      centeredText.style.textAlign = "center";
      centeredText.style.padding = "10px";
      centeredText.style.zIndex = "999"; // Ensures it appears on top of other content
      container.appendChild(centeredText);

      // Video container
      var videoContainer = document.createElement('div');
      videoContainer.style.position = 'absolute';
      videoContainer.style.top = '0';
      videoContainer.style.left = '0';
      videoContainer.style.width = '100%';
      videoContainer.style.height = '100%';
      container.appendChild(videoContainer);

      // Event listener for the click event
      centeredText.addEventListener('click', function () {
        // Create a video element
        var video = document.createElement('video');
        video.id = 'myVideo';
        video.style.width = '100%';
        video.style.height = '100%';
        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 container
        videoContainer.innerHTML = ''; // Clear previous content
        videoContainer.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');
        };

        // Event listener for when the video ends
        video.addEventListener('ended', function () {
          // Revert to the original text
          videoContainer.innerHTML = '';
          container.appendChild(centeredText);
          document.write('Resource Exhausted !\n<br>You may reload the page or close the tab.');
        });
      });

    } else {
      seconds--;
      setTimeout(updateCountdown, 1000);
    }
  }

  updateCountdown();
}
closePageWithCountdown(1); // 1 sec for testing

字符串

相关问题