2 кнопки рядом под моим увеличенным изображением

Я хочу создать 2 кнопки внизу моего изображения, когда вы нажимаете, чтобы увеличить изображение. До сих пор мое изображение работало по щелчку для увеличения, но я изо всех сил пытаюсь получить две кнопки внизу на моем увеличенном изображении. Если бы кто-то мог помочь, было бы здорово!

Я также пытаюсь заставить кнопки нажимать на другую всплывающую форму. Где они могут заказать или узнать об этом конкретном продукте. Пожалуйста, помогите мне, очень мало времени. Спасибо

Вот код, который я использую:

// 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.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
}

// 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";
}
/* Style the Image Used to Trigger the Modal */
#myImg {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

#myImg: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: transparent; /* Fallback color */
    background-color: transparent; /* 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: #000;
    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%;
    }
}
<img id = "myImg" src = "Almond.jpg" alt = "almonds in factory" 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>

попробуйте это codepen.io/ajanth2012/pen/MXaPpp

Ajanth 05.06.2018 09:40
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
1
66
1

Ответы 1

Это то, что вам нужно? (Добавьте две кнопки в Modal под увеличенным изображением)

Если я неправильно понял ваш вопрос, пожалуйста, сообщите мне, спасибо!

Отредактировано

Советы для нескольких модальных слоев:

  1. Создайте новый модальный div.

  2. Установите для модального div другой z-index.

  3. Лучше сделать так, чтобы модальный div имел фон, чтобы избежать наложения.

Добавьте кнопку показа, чтобы показать другое модальное окно:

// Get the modal
var modal1 = document.getElementById('myModal1');
var modal2 = document.getElementById('myModal2');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg1 = document.getElementById("img01");
var modalImg2 = document.getElementById("img02");
var captionText1 = document.getElementById("caption1");
var captionText2 = document.getElementById("caption2");
var enlarge = document.getElementById("enlarge");
var close_btn = document.getElementById("close-btn");
var close1 = document.getElementById("close1");
var close2 = document.getElementById("close2");
var show = document.getElementById("show");
img.onclick = function(){
    modal1.style.display = "block";
    modalImg1.src = this.src;
    captionText1.innerHTML = this.alt;
}
show.onclick = function(){
    modal2.style.display = "block";
    modalImg2.src = modalImg1.src;
    captionText2.innerHTML = "I'm the new " + captionText1.innerHTML;
}

// When the user clicks on <span> (x), close the modal
close_btn.onclick = function() { 
    modal1.style.display = "none";
};
close1.onclick = function() { 
    modal1.style.display = "none";
};
close2.onclick = function() { 
    modal2.style.display = "none";
};
/* Style the Image Used to Trigger the Modal */
#myImg {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

#myImg: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: transparent; /* Fallback color */
    background-color: transparent; /* Black w/ opacity */
}
#myModal2 {

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

/* Caption of Modal Image */
#caption1,#caption2 {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}
#buttons {
    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 */
#close1, #close2 {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #000;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

#close1:hover,
#close1:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}
#close2:hover,
#close2: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%;
    }
}
<img id = "myImg" src = "Almond.jpg" alt = "almonds in factory" width = "300" height = "200">
  
<!-- The Modal -->
<div id = "myModal1" class = "modal">
  <span id = "close1">&times;</span>
  <img class = "modal-content" id = "img01">
  <div id = "buttons">
  <button id = "show">show another</button>
  <button id = "close-btn">close modal</button>
  </div>
  <div id = "caption1"></div>
</div>

<!-- The Modal -->
<div id = "myModal2" class = "modal">
  <span id = "close2">&times;</span>
  <img class = "modal-content" id = "img02">
  <div id = "caption2"></div>
</div>

Большое спасибо Терри, отлично работает! Однако есть одна проблема: есть ли способ отображения всплывающего окна в полноэкранном режиме? Я работаю с wpbakery. Так что он открывается только до размера "строки", а не экрана. Твоя легенда лол

OverReactor 05.06.2018 11:25

вот один пример: stackoverflow.com/questions/18432394/…

Terry Wei 05.06.2018 11:32

модальный div, помещенный под тело, может показывать 100% ширину 100% высоту для полноэкранного режима

Terry Wei 05.06.2018 11:33

Сладкий, работает ... Еще раз спасибо Терри очень благодарен за помощь, проблема в том, что мне это нужно, чтобы работать с моим изображением, и когда я дублирую html-часть, изображение не щелкает, чтобы увеличить. Был бы очень признателен за помощь.

OverReactor 05.06.2018 13:11

Это в основном для галереи

OverReactor 05.06.2018 13:19

Вы должны позволить всем вашим изображениям связывать событие щелчка и заметить, что идентификатор не должен дублироваться. Если вам нужно добавлять изображения динамически, убедитесь, что они действительно связывают событие.

Terry Wei 06.06.2018 02:33

Хорошо, надеюсь, этот ответ вам поможет.

Terry Wei 14.06.2018 09:43

Другие вопросы по теме