¿Cómo cambiar la imagen dinámicamente cuando el usuario se desplaza usando JavaScript?

Vamos a agregar la funcionalidad a nuestra página web para que cada vez que el usuario se desplace hacia arriba o hacia abajo en la imagen, la imagen cambie. Hemos usado solo 3 imágenes, pero se puede expandir fácilmente para múltiples imágenes.
Mantenemos las imágenes una encima de la otra, esto asegura que solo una imagen sea visible a la vez. Cuando nos desplazamos, disminuimos la coordenada z de la imagen actual e incrementamos la coordenada z de la nueva imagen. Al hacer esto, la nueva imagen se superpone a la imagen anterior y aparece encima de todas las imágenes y se vuelve visible.
 

  • Código HTML: Se utiliza para crear una estructura básica para incluir imágenes. 
     

html

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="utf-8" />
    <title>
        Change Image Dynamically
        when User Scrolls
    </title>
</head>
 
<body>
<h1>GeeksforGeeks</h1>
<b>A Computer Science Portal for Geeks</b>
    <div id="scroll-image">
        <img src="CSS.png" class="test" />
        <img src="html.png" class="test" />
        <img src="php.png" class="test" />
    </div>
</body>
 
</html>                   
  • Código CSS: Css se utiliza para diseñar la estructura. La propiedad de posición es lo más importante aquí. Hará que todas las imágenes aparezcan una encima de la otra.
     

html

<style>
    body {
        text-align: center;
    }
    h1 {
        color: green;
    }
    img {
        position: absolute;
        left: 300px;
    }
</style>
  • Código Javascript: En esta sección añadiremos código JavaScript para realizar el scroll sobre la imagen.
     

javascript

<script>
    window.onload = function() {
  
        // Index of current image
        // which is on display
        var imageIndex = 0;
  
        // Object array of all the
        // images of class test
        var images =
            document.getElementsByClassName('test');
  
        // This tells us if mouse if over
        // image or not, We only change
        // image if mouse if over it
        var isMouseOverImage = false;
  
        // Object of parent element
        // containing all images
        var scrollImages =
            document.getElementById('scroll-image');
  
        // Stores the current scroll co-ordinates
        // so that the window don't scroll down
        // while scrolling the images
        var x, y;
  
        // This function sets the scroll to x, y
        function noScroll() {
            window.scrollTo(x, y);
        }
  
        // The following event id fired once when
        // We hover mouse over the images
        scrollImages.addEventListener(
                "mouseenter", function() {
  
            // We store the current page
            // offset to x,y
            x = window.pageXOffset;
            y = window.pageYOffset;
  
            // We add the following event to
            // window object, so if we scroll
            // down after mouse is over the
            // image we can avoid scrolling
            // the window
            window.addEventListener("scroll", noScroll);
             
            // We set isMouseOverImage to
            // true, this means Mouse is
            // now over the image
            isMouseOverImage = true;
        });
  
        // The following function is fired
        // when mouse is no longer over
        // the images
        scrollImages.addEventListener(
                "mouseleave", function() {
  
            // We set isMouseOverImage to
            // false, this means mouse is
            // not over the image
            isMouseOverImage = false;
  
            // We remove the event we previously
            // added because we are no longer
            // over the image, the scroll will
            // now scroll the window
            window.removeEventListener(
                        "scroll", noScroll);
        });
  
        // The following function is called
        // when we move mouse wheel over
        // the images
        scrollImages.addEventListener(
                    "wheel", function(e) {
                             
            // We check if we are over
            // image or not
            if (isMouseOverImage) {
                var nextImageIndex;
  
                // The following condition
                // finds the next image
                // index depending if we
                // scroll up or scroll down
                if (e.deltaY > 0)
                    nextImageIndex = (imageIndex + 1)
                                     % images.length;
                else
                    nextImageIndex =
                            (imageIndex - 1
                            + images.length)
                            % images.length;
  
                // We set the z index of current
                // image to 0
                images[imageIndex].style.zIndex = "0";
                     
                // We set the z index of next
                // image to 1, this makes
                // The new image appear on top
                // of old image
                images[nextImageIndex].style.zIndex = "1";
                imageIndex = nextImageIndex;
            }
        });
    }
</script>

Solución final: en esta sección combinaremos las tres secciones anteriores. 
 

JavaScript

<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8" />
    <title>
        Change image dynamically
        when user scrolls
    </title>
     
    <style>
        body {
            text-align: center;
        }
        h1 {
            color: green;
        }
        img {
            position: absolute;
            left: 300px;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
     
    <b>A Computer Science Portal for Geeks</b>
     
    <div id="scroll-image">
        <img src="CSS.png" class="test" />
        <img src="html.png" class="test" />
        <img src="php.png" class="test" />
    </div>
     
    <script>
        window.onload = function() {
      
            // Index of current image
            // which is on display
            var imageIndex = 0;
      
            // Object array of all the
            // images of class test
            var images =
                document.getElementsByClassName('test');
      
            // This tells us if mouse if over
            // image or not, We only change
            // image if mouse if over it
            var isMouseOverImage = false;
      
            // Object of parent element
            // containing all images
            var scrollImages =
                document.getElementById('scroll-image');
      
            // Stores the current scroll co-ordinates
            // so that the window don't scroll down
            // while scrolling the images
            var x, y;
      
            // This function sets the scroll to x, y
            function noScroll() {
                window.scrollTo(x, y);
            }
      
            // The following event id fired once when
            // We hover mouse over the images
            scrollImages.addEventListener(
                    "mouseenter", function() {
      
                // We store the current page
                // offset to x,y
                x = window.pageXOffset;
                y = window.pageYOffset;
      
                // We add the following event to
                // window object, so if we scroll
                // down after mouse is over the
                // image we can avoid scrolling
                // the window
                window.addEventListener("scroll", noScroll);
                 
                // We set isMouseOverImage to
                // true, this means Mouse is
                // now over the image
                isMouseOverImage = true;
            });
      
            // The following function is fired
            // when mouse is no longer over
            // the images
            scrollImages.addEventListener(
                    "mouseleave", function() {
      
                // We set isMouseOverImage to
                // false, this means mouse is
                // not over the image
                isMouseOverImage = false;
      
                // We remove the event we previously
                // added because we are no longer
                // over the image, the scroll will
                // now scroll the window
                window.removeEventListener(
                            "scroll", noScroll);
            });
      
            // The following function is called
            // when we move mouse wheel over
            // the images
            scrollImages.addEventListener(
                        "wheel", function(e) {
                                 
                // We check if we are over
                // image or not
                if (isMouseOverImage) {
                    var nextImageIndex;
      
                    // The following condition
                    // finds the next image
                    // index depending if we
                    // scroll up or scroll down
                    if (e.deltaY > 0)
                        nextImageIndex = (imageIndex + 1)
                                         % images.length;
                    else
                        nextImageIndex =
                                (imageIndex - 1
                                + images.length)
                                % images.length;
      
                    // We set the z index of current
                    // image to 0
                    images[imageIndex].style.zIndex = "0";
                         
                    // We set the z index of next
                    // image to 1, this makes
                    // The new image appear on top
                    // of old image
                    images[nextImageIndex].style.zIndex = "1";
                    imageIndex = nextImageIndex;
                }
            });
        }
    </script>
</body>
  
</html>

Producción: 
 

Nota: El código anterior cambiará la imagen solo si el mouse está sobre la imagen.
 

Publicación traducida automáticamente

Artículo escrito por Archaic y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *