1

He encontrado este Modal propuesto por la W3C y parece una solución sencilla; pero está pensada para utilizarlo en una imagen por página, ya que los selectores son IDs. He probado a cambiar a clases y cambiar el selector, pero sigue sin funcionar.

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal_img

Habría 3 o 4 imágenes por página que me gustaría que se pudieran ampliar. Las imágenes se meterían directamente desde el HTML, o sea que se podría cambiar una cifra a cada clase para cada imagen de forma sencilla.

Como apunte: Habeís podido observar que mi nivel de Javascript es mínimo. Así que, por favor, intentad no ser demasiado técnicos en la explicación. En cuanto al HTML, CSS, selectores, etc ningún problema.

Gracias de antemano.

3 respuestas 3

0

Sin jquery, ocupando tu mismo código.

No encuentro engorroso usar javascript y lo menos de librerías posible, aunque ya es como cada uno se acomode mejor.

En CSS, cambié la consulta al modal a id pues es único para todas las imágenes que quieras. Y el de la imagen la cambié a class para indicar que pueden ser varias imágenes a seleccionar en el mismo archivo.

Agregué una lista de ids de imagen, pero puede reemplazarse por una búsqueda de clase, solo que no se me ocurrió en ese momento. Incluí las cuatro imágenes de donde viene la que usaste en tu ejemplo.

Te dejo el link para ver la solución en TryIt de W3Schools

Usé la misma estructura de tu código, pero como muchos, te recomiendo que uses archivos independientes para estilo y scripts.

1
  • Es perfecto. Mil gracias!! el 30 mar. 2017 a las 19:33
0

En realidad es muy sencillo con jquery, mira el ejemplo:

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
//var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
$("img").click(function(){
    //modal.style.display = "block";
    $("#myModal").css("display","block");
    $("#img01").attr("src",$(this).attr('src'));
    $("#caption").text( $(this).attr('alt'));
    
    //console.log($(this).attr('src'));
});

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
    modal.style.display = "none";
}
img {
   border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

img:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

/* Caption of Modal Image */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* Add Animation */
.modal-content, #caption {    
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)} 
    to {-webkit-transform:scale(1)}
}

@keyframes zoom {
    from {transform:scale(0)} 
    to {transform:scale(1)}
}

/* The Close Button */
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
    .modal-content {
        width: 100%;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>

<img id="myImg" src="https://www.w3schools.com/howto/img_fjords.jpg" alt="Trolltunga, Norway" width="300" height="200">

<img id="myImg2" src="http://www.mastiposde.com/wp-content/uploads/Paisaje-Natural.jpg" alt="imagen 2" width="300" height="200">

<img id="myImg3" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Sasso_lungo_da_passo_pordoi.jpg/270px-Sasso_lungo_da_passo_pordoi.jpg" alt="imagen 3" width="300" height="200">

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>


</body>
</html>

Lo que hace el código es:

 $("img").click(function(){//Asigna el click a TODAS LAS imagenes de la pagina
        //modal.style.display = "block";
        $("#myModal").css("display","block");//Muestro el modal
        $("#img01").attr("src",$(this).attr('src'));//Paso la imagen al modal
        $("#caption").text( $(this).attr('alt'));//Paso la informacion al caption

        //console.log($(this).attr('src'));
    });
2
  • 1
    Muchas gracias por tu respuesta Cristina. Aunque realmente no me merece la pena cargar jQuery para solucionar esto. Te doy un voto positivo porque puede ayudar a otra persona :) el 30 mar. 2017 a las 19:35
  • Ok :), igual manera se puede realizar sin jquery el 30 mar. 2017 a las 19:40
0

Antes de hacer un manejo tan en crudo del DOM en HTML recomendaría usar algo como JQuery para que no sea tan engorroso el manejo.

La idea de la solución es en ves de utilizar ID que son único, seleccionar todas las imágenes de la galería por un selector de clase, o agregarle un evento OnClick en base a ello la siguiente solución es mas sencilla.

Te dejo un ejemplo funcional del mismo

function mostrarModal(obj) {
  var imgSrc = $(obj).attr('src');
  $("#img01").attr('src', imgSrc);
  $("#myModal").show();
}

function ocultarModal() { 
    $("#myModal").hide();
}
.image {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

.image:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

/* Caption of Modal Image */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* Add Animation */
.modal-content, #caption {    
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)} 
    to {-webkit-transform:scale(1)}
}

@keyframes zoom {
    from {transform:scale(0)} 
    to {transform:scale(1)}
}

/* The Close Button */
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
    .modal-content {
        width: 100%;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="myImg1" class="image" src="https://www.w3schools.com/howto/img_fjords.jpg"
onclick="mostrarModal(this)" alt="Trolltunga, Norway" width="300" height="200">

<img id="myImg2" class="image" src="https://www.w3schools.com/howto/img_fjords.jpg" onclick="mostrarModal(this)" alt="Trolltunga, Norway" width="300" height="200">

<img id="myImg2" class="image" src="https://www.w3schools.com/howto/img_fjords.jpg" onclick="mostrarModal(this)" alt="Trolltunga, Norway" width="300" height="200">


<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close" onclick="ocultarModal()">&times;</span>
  <img class="modal-content" id="img01">
</div>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.