Как получить фоновое изображение нескольких div и использовать их в качестве источника модальных изображений с JavaScript? - PullRequest
0 голосов
/ 10 марта 2020

Я создаю галерею изображений, и я хотел бы иметь возможность открывать полноразмерное изображение при нажатии.

Проблема в том, что я не использую теги img, я создаю его, используя div и background-image.

Я знаю, как сделать это для одного изображения, используя id, код ниже. Тем не менее, я не могу заставить его работать с несколькими div, используя classes. Это может быть просто, но я знаю basi c JavaScript, которого недостаточно для этой задачи. Я много искал по этому вопросу безрезультатно. Я пробовал лайтбокс, но не мог заставить его работать с фоновым изображением. Буду признателен за любую помощь, даже несколько советов, чтобы поставить меня на правильный путь.

var modal = document.getElementById("myModal");
var img = document.getElementById("tehran");
var backgroundImage = img.style.backgroundImage.slice(4, -1).replace(/"/g, '');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function() {
  modal.style.display = "block";
  modalImg.src = backgroundImage;
}
// close the modal
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
  modal.style.display = "none";
}
.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;
}

.img {
  display: block;
  width: 200px;
  height: 100%;
  margin-right: 10px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  cursor: pointer;
}

.img-container {
  display: flex;
  height: 100px;
  min-height: 20rem;
}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.9);
}

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@keyframes zoom {
  from {
    transform: scale(0)
  }
  to {
    transform: scale(1)
  }
}
<body>
  <div class="img-container">
    <div id="tehran" class="img" style="background-image: url(https://images.unsplash.com/photo-1524567492592-cee28084482e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=600&q=60)"></div>
    <div id="masuleh" class="img" style="background-image: url(https://images.unsplash.com/photo-1567317255448-8e6c04e22114?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80)"></div>
    <div id="zanjan" class="img" style="background-image: url(https://images.unsplash.com/photo-1518727577784-f62f1115eefb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80)"></div>
  </div>

  <!-- The Modal -->
  <div id="myModal" class="modal">

    <!-- The Close Button -->
    <span class="close">&times;</span>

    <!-- Modal Content -->
    <img id="img01" class="modal-content">
    <div id="caption"></div>
  </div>
</body>

Ответы [ 2 ]

1 голос
/ 10 марта 2020

Вы должны выбрать все элементы (по class ), затем l oop через них, чтобы прикрепить событие ( click ).

Также с img имеет предопределенное значение, я предлагаю вам использовать другое имя как class , отличное от img .

Вы можете попробовать следующее путь:

var modal = document.getElementById("myModal");
var img = document.querySelectorAll(".myImg");

var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.forEach(function(img){
  var backgroundImage = img.style.backgroundImage.slice(4, -1).replace(/"/g, '');
  img.onclick = function() {
    modal.style.display = "block";
    modalImg.src = backgroundImage;
  }
});
// close the modal
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
  modal.style.display = "none";
}
.img-container {
  display: flex;
  height: 100px;
  min-height: 20rem;
}

.myImg {
  display: block;
  width: 200px;
  height: 100%;
  margin-right: 10px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  cursor: pointer;
}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.9);
}

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@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;
}
<body>
  <div class="img-container">
    <div id="tehran" class="myImg" style="background-image: url(https://images.unsplash.com/photo-1524567492592-cee28084482e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=600&q=60)"></div>
    <div id="masuleh" class="myImg" style="background-image: url(https://images.unsplash.com/photo-1567317255448-8e6c04e22114?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80)"></div>
    <div id="zanjan" class="myImg" style="background-image: url(https://images.unsplash.com/photo-1518727577784-f62f1115eefb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80)"></div>
  </div>

  <!-- The Modal -->
  <div id="myModal" class="modal">

    <!-- The Close Button -->
    <span class="close">&times;</span>

    <!-- Modal Content -->
    <img id="img01" class="modal-content">
    <div id="caption"></div>
  </div>
</body>
1 голос
/ 10 марта 2020

(я также внес css изменений, чтобы модальное изображение не переполняло страницу)

var modal = document.getElementById("myModal");
Array.from(document.querySelectorAll('.img-container .img')).forEach(function(img){
img.onclick = function() {
  var backgroundImage = img.style.backgroundImage.slice(4, -1).replace(/"/g, '');
  modal.style.display = "flex";
  modalImg.src = backgroundImage;
}
});
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");

// close the modal
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
  modal.style.display = "none";
}
.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;
}

.img {
  display: block;
  width: 200px;
  height: 100%;
  margin-right: 10px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  cursor: pointer;
}

.img-container {
  display: flex;
  height: 100px;
  min-height: 20rem;
}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.9);
  justify-content: center;
  align-items: center;
}

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  max-height: 80%;
  object-fit: contain;
  -o-object-fit: contain;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@keyframes zoom {
  from {
    transform: scale(0)
  }
  to {
    transform: scale(1)
  }
}
<body>
  <div class="img-container">
    <div id="tehran" class="img" style="background-image: url(https://images.unsplash.com/photo-1524567492592-cee28084482e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=600&q=60)"></div>
    <div id="masuleh" class="img" style="background-image: url(https://images.unsplash.com/photo-1567317255448-8e6c04e22114?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80)"></div>
    <div id="zanjan" class="img" style="background-image: url(https://images.unsplash.com/photo-1518727577784-f62f1115eefb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80)"></div>
  </div>

  <!-- The Modal -->
  <div id="myModal" class="modal">

    <!-- The Close Button -->
    <span class="close">&times;</span>

    <!-- Modal Content -->
    <img id="img01" class="modal-content">
    <div id="caption"></div>
  </div>
</body>
...