Dada una página web, y la tarea es iniciar el control deslizante solo después de que el video termine con JavaScript.
Sintaxis
En HTML:
<video onended="myScript">
En JavaScript:
1. Usando la función personalizada:
video.onended=function(){myScript};
2. Usando el método addEventListener():
video.addEventListener("ended", myScript);
Ejemplo:
Javascript
var video = document.getElementById("GFG"); video.onended = function() { alert("The video has ended now"); };
Ahora, llegando a nuestra funcionalidad requerida, usamos este evento para activar la siguiente diapositiva solo después de que el video haya terminado.
Algoritmo:
- Escriba la parte HTML de la página web y también agregue el video.
- Agregue estilo si es necesario usando CSS o cualquiera de las bibliotecas frontales.
- Obtenga el elemento por su selector o clase o id en JavaScript y use los eventos onplaying y onended del DOM para realizar la diapositiva solo después de que finalice el video.
Pasos:
Paso 1: escriba el marcado HTML y agregue el elemento de video en su archivo HTML.
index.html
<!DOCTYPE html> <html> <body> <video id="Vid" width="320" height="176" controls> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20210219152742/video.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> <div> <h2 id="next">Welcome to GeeksForGeeks</h2> <p class="text"> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassadors in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </p> <p class="text"> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassadors in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </p> </div> </body> </html>
Aquí, he usado el elemento de video y el elemento fuente de HTML para mantenerlo preciso y controlable. He usado un video de archivo como referencia aquí.
Paso 2: agregar el estilo en el archivo CSS (o cualquier otro según su elección).
style.css
/* Increasing the size of video element */ #Vid { height: 35rem; width: 50rem; } /* Aligning the content and text and adding really basic styling */ body { align-items: center; text-align: center; color: green; }
El CSS es completamente personalizado y opcional y podemos añadirle estilo a nuestro gusto.
Paso 3: agregue JavaScript para permitir que la página se deslice o se desplace solo después del final del video.
- Agregamos la función de reproducción automática a nuestro video para que el usuario reproduzca el video tan pronto como ingrese a la página. Una buena práctica es silenciar el video si está en reproducción automática. Mi video no contiene un sonido aquí, así que no lo he usado.
- Ocultamos el desplazamiento de la página, por lo tanto, no permitimos que la página se deslice o se desplace mientras se reproduce el video con la ayuda de la función de reproducción de JavaScript y la propiedad de desbordamiento de CSS.
- Finalmente añadimos nuestro último pero más importante fragmento de código. Usamos la función finalizada de JavaScript, eliminamos la propiedad de desbordamiento oculta, usamos la función scrollIntoView() en JavaScript.
Código JavaScript:
Javascript
var v = document.getElementById("Vid"); v.autoplay = true; v.load(); v.onplaying = function() { document.body.style.overflow = 'hidden'; }; // Executes only when the video ends v.onended = function() { // Enabling the scroller document.body.style.overflow = ''; // Scrolling to the next element by // linking to its Id document.getElementById("next").scrollIntoView(); };
Aquí, eliminamos la propiedad de desbordamiento y habilitamos el desplazamiento cuando el video deja de reproducirse, y también nos desplazamos al siguiente elemento.
Código final: aquí está el código HTML completo para todo
HTML
<!DOCTYPE html> <html> <head> <style> /* Increasing the size of video element */ #Vid { height: 35rem; width: 50rem; } /* Aligning the content and text and adding really basic styling */ body { align-items: center; text-align: center; color: green; } .text { margin: 0% 20%; } </style> </head> <body> <video id="Vid" width="320" height="176" controls> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20210219152742/video.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> <div> <h2 id="next">Welcome to GeeksForGeeks</h2> <p class="text"> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassadors in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </p> <p class="text"> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassadors in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </p> </div> <script> // Storing the video element through its id var v = document.getElementById("Vid"); // Adding the autoplay feature v.autoplay = true; v.load(); // Hiding the scroller while video is playing v.onplaying = function() { document.body.style.overflow = 'hidden'; }; // Executes only when the video ends v.onended = function() { // Enabling the scroller document.body.style.overflow = ''; // Scrolling to the next element by // linking to its Id document.getElementById("next").scrollIntoView(); }; </script> </body> </html>
Producción:
Publicación traducida automáticamente
Artículo escrito por dikshapatro y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA