Nano Hash - криптовалюты, майнинг, программирование

Как изменить этот код для модального окна, чтобы он работал с классом вместо href?

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

.wrapper{
    margin-top:125px;
}
img {
    display:block;
    width:100%;
    height:auto;
}
.portfolio-box {
    display:flex;
    flex-wrap:wrap;
    flex:1;
    flex-direction:row;
    justify-content:center;
}
.portfolio-box > div {
    display:flex;
    justify-content:flex-start;
    flex:1;
    flex-direction:column;
    margin:5px;
    margin-bottom: 40px;
}
.thumb-outer{
    /*Just a  placeholder*/
}
.thumbgrid{
    position:relative;
    display:inline-block;
}
.thumbgrid .inner_box{
    position: absolute;
    width:100.1%;
    height:100%;
    background:rgba(80, 145, 144, 0.64);
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    border:1px solid #000;
    border-radius:2px;
}
.thumbgrid .inner_box span{
    color:#4f9190;
    font-family:bonvenocf-light;
    font-weight:bold;
    font-size:16px;
    text-align: center;
    background:#fff;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:101.2%;
}
.synopsis{
    vertical-align:top;
    text-align:justify;
    margin:0 3px 0 3px;
    display: inline-block;
}
<div class="wrapper">

<section>
<!--Start of Portfolio-->
<div class="portfolio-box">
<!--Thumb 1-->
<div class="thumb-outer">
<div class="thumbgrid">
  <img src="https://i0.wp.com/ukhumanrightsblog.com/wp-content/uploads/2013/06/seo-marketing-320x200.jpg">
  <div class="inner_box">
  <span>Title 1</span>
</div>
</div>
   <div class="synopsis">
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse placerat diam eget magna dignissim malesuada.
     </div>
</div>
<!--End Of Thumb-->

<!--Thumb 2-->
<div class="thumb-outer">
<div class="thumbgrid">
  <img src="https://i0.wp.com/ukhumanrightsblog.com/wp-content/uploads/2013/06/seo-marketing-320x200.jpg">
  <div class="inner_box">
  <span>Title 2</span>
</div>
</div>
   <div class="synopsis">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse placerat diam eget magna dignissim malesuada.
     </div>
</div>
<!--End Of Thumb-->

<!--Thumb 3-->
<div class="thumb-outer">
<div class="thumbgrid">
  <img src="https://i0.wp.com/ukhumanrightsblog.com/wp-content/uploads/2013/06/seo-marketing-320x200.jpg">
  <div class="inner_box">
  <span>Title 3</span>
</div>
</div>
   <div class="synopsis">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse placerat diam eget magna dignissim malesuada.
     </div>
</div>
<!--End Of Thumb-->

<!--Thumb 4-->
<div class="thumb-outer">
<div class="thumbgrid">
  <img src="https://i0.wp.com/ukhumanrightsblog.com/wp-content/uploads/2013/06/seo-marketing-320x200.jpg">
  <div class="inner_box">
  <span>Title 4</span>
</div>
</div>
   <div class="synopsis">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse placerat diam eget magna dignissim malesuada.
     </div>
</div>
<!--End Of Thumb-->

</div><!--End of Portfolio-->
</div>

Я нашел 2 кода, которые я мог бы использовать для открытия галерей в модальном режиме, но ни один из них не дал мне желаемого результата. Приведенный ниже код открывает модальный класс через класс, но по какой-то причине кнопка закрытия X не работает, а модальное закрытие не работает, когда вы щелкаете за пределами изображения.

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

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");


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

// When the user clicks the button, open the modal 
btn[0].onclick = function() {
    modal[0].style.display = "block";
}

btn[1].onclick = function() {
    modal[1].style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span[0].onclick = function() {
    modal[0].style.display = "none";
}

span[1].onclick = function() {
    modal[1].style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
body {font-family: Arial, Helvetica, sans-serif;}

/* 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.4); /* Black w/ opacity */
}
img{
width:100%;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.4s;
}
/* Modal Content */
.modal-content {
  position: relative;
  margin: auto;
  padding: 0;
  width: 80%;
}

/* Add Animation */
@-webkit-keyframes animatetop {
  from {top:-300px; opacity:0} 
  to {top:0; opacity:1}
}

@keyframes animatetop {
  from {top:-300px; opacity:0}
  to {top:0; opacity:1}
}

/* The Close Button */
.close {
  color: red;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<button class="myBtn">Open Modal</button>

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

  <!-- Modal content -->
  <div class="modal-content">
      <span class="close">×</span>
<img src="https://cdn-images-1.medium.com/max/2000/1*6cpWeq1_VMYtd1LgHwxKug.jpeg">
  </div>

</div>

Код ниже работает отлично, но он открывает модальное окно через href. Из того, что я читал, div нельзя превратить в ссылки. Я пытался возиться с обоими кодами в надежде, что смогу заставить один из них работать правильно, но я все еще изучаю Javascript и не смог понять ни один из них.

Я надеюсь получить некоторую помощь с любым кодом. С 1-м модальным я хотел бы, чтобы кнопка закрытия и закрытие, щелкнув за пределами модального окна, работали. Со вторым кодом я хотел бы иметь возможность использовать класс для открытия модального окна вместо тега привязки, чтобы, когда пользователь нажимал на элементы div, он открывал модальную галерею.

// Get the button that opens the modal
var btn = document.querySelectorAll("button.modal-button");

// All page modals
var modals = document.querySelectorAll('.modal');

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

// When the user clicks the button, open the modal
for (var i = 0; i < btn.length; i++) {
 btn[i].onclick = function(e) {
    e.preventDefault();
    modal = document.querySelector(e.target.getAttribute("href"));
    modal.style.display = "block";
 }
}

// When the user clicks on <span> (x), close the modal
for (var i = 0; i < spans.length; i++) {
 spans[i].onclick = function() {
    for (var index in modals) {
      if (typeof modals[index].style !== 'undefined') modals[index].style.display = "none";    
    }
 }
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
     for (var index in modals) {
      if (typeof modals[index].style !== 'undefined') modals[index].style.display = "none";    
     }
    }
}
/* 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.4); /* Black w/ opacity */
}
img{
width:100%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s;
}
/* Modal Content */
.modal-content {
    position: relative;
    margin: auto;
    padding: 0;
    width: 80%;
}

/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
<button class="modal-button" href="#myModal1">Open Modal</button>

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

  <!-- Modal content -->
  <div class="modal-content">
      <span class="close">×</span>
<img src="https://cdn-images-1.medium.com/max/1000/1*6cpWeq1_VMYtd1LgHwxKug.jpeg">
  </div>

</div>


  • Возможно, вы захотите ограничить пример кода только проблемными частями. 07.01.2019
  • Я думал, что если я добавлю меньше кода или не добавлю весь код, люди не увидят именно то, о чем я говорю. Я думал, что больше информации, как правило, лучше, когда дело доходит до решения кода. 07.01.2019

Ответы:


1

Ваш window.click отменял все.

РЕДАКТИРОВАТЬ: исправлено, чтобы обеспечить правильное закрытие за пределами модального окна. ПРИМЕЧАНИЕ. Удалено window.click как необязательное.

document.addEventListener('DOMContentLoaded', function() {

  let modal = document.querySelector('.modal');
  let modalContent = document.querySelector('.modal-content');
  let btn = document.querySelector('.myBtn');
  let closeSpan = document.querySelector('.close');
  
  btn.addEventListener('click', function() {
    console.log('btn click');
    console.log(modal);
    modal.style.display = 'block';    
  });
  
  closeSpan.addEventListener('click', function() {
    modal.style.display = 'none';  
  });
  
  modal.addEventListener('click', function(event) {
    console.log(event.target.id);
    if(event.target.id === 'myModal') }
      modal.style.display = 'none';
    } 
  });  
});
body {
  font-family: Arial, Helvetica, sans-serif;
}


/* 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.4);
  /* Black w/ opacity */
}

img {
  width: 100%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.4s;
}


/* Modal Content */

.modal-content {
  position: relative;
  margin: auto;
  padding: 0;
  width: 80%;
}


/* Add Animation */

@-webkit-keyframes animatetop {
  from {
    top: -300px;
    opacity: 0
  }
  to {
    top: 0;
    opacity: 1
  }
}

@keyframes animatetop {
  from {
    top: -300px;
    opacity: 0
  }
  to {
    top: 0;
    opacity: 1
  }
}


/* The Close Button */

.close {
  color: red;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<button class="myBtn">Open Modal</button>

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

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <img src="https://cdn-images-1.medium.com/max/2000/1*6cpWeq1_VMYtd1LgHwxKug.jpeg">
  </div>

</div>

07.01.2019
  • Большое спасибо. По какой-то причине он все еще не закрывается, когда вы щелкаете за пределами модального содержимого. 07.01.2019
  • Исправлено. Даже лучше без глобального окна. Нажмите сейчас :) 07.01.2019
  • Спасибо еще раз. Кнопка не работала, но я смог понять, как это исправить. Последние несколько строк были проблемой ... Я изменил его на приведенный ниже, и теперь он отлично работает. если (event.target.id === 'myModal'); modal.style.display = 'нет'; }); }); 07.01.2019
  • Новые материалы

    Кластеризация: более глубокий взгляд
    Кластеризация — это метод обучения без учителя, в котором мы пытаемся найти группы в наборе данных на основе некоторых известных или неизвестных свойств, которые могут существовать. Независимо от..

    Как написать эффективное резюме
    Предложения по дизайну и макету, чтобы представить себя профессионально Вам не позвонили на собеседование после того, как вы несколько раз подали заявку на работу своей мечты? У вас может..

    Частный метод Python: улучшение инкапсуляции и безопасности
    Введение Python — универсальный и мощный язык программирования, известный своей простотой и удобством использования. Одной из ключевых особенностей, отличающих Python от других языков, является..

    Как я автоматизирую тестирование с помощью Jest
    Шутка для победы, когда дело касается автоматизации тестирования Одной очень важной частью разработки программного обеспечения является автоматизация тестирования, поскольку она создает..

    Работа с векторными символическими архитектурами, часть 4 (искусственный интеллект)
    Hyperseed: неконтролируемое обучение с векторными символическими архитектурами (arXiv) Автор: Евгений Осипов , Сачин Кахавала , Диланта Хапутантри , Тимал Кемпития , Дасвин Де Сильва ,..

    Понимание расстояния Вассерштейна: мощная метрика в машинном обучении
    В обширной области машинного обучения часто возникает необходимость сравнивать и измерять различия между распределениями вероятностей. Традиционные метрики расстояния, такие как евклидово..

    Обеспечение масштабируемости LLM: облачный анализ с помощью AWS Fargate и Copilot
    В динамичной области искусственного интеллекта все большее распространение получают модели больших языков (LLM). Они жизненно важны для различных приложений, таких как интеллектуальные..