0

Как можно сделать, чтобы модальное окно открывалось не через оду кнопку, а через две или три Например: КНОПКА1 и КНОПКА2 - и обе эти кнопки открывают одно и тоже модальное окно (содержимое окна НЕ меняется)

(желательно чтобы не использовать Bootstrap и JQuery)

Код модального окна:

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

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

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

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

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.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";
    }
}
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    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 */
    -webkit-animation-name: fadeIn; /* Fade in the background */
    -webkit-animation-duration: 0.4s;
    animation-name: fadeIn;
    animation-duration: 0.4s
}

/* Modal Content */
.modal-content {
    position: fixed;
    bottom: 0;
    background-color: #fefefe;
    width: 100%;
    -webkit-animation-name: slideIn;
    -webkit-animation-duration: 0.4s;
    animation-name: slideIn;
    animation-duration: 0.4s
}

/* 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;
}

.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

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

@keyframes slideIn {
    from {bottom: -300px; opacity: 0}
    to {bottom: 0; opacity: 1}
}

@-webkit-keyframes fadeIn {
    from {opacity: 0} 
    to {opacity: 1}
}

@keyframes fadeIn {
    from {opacity: 0} 
    to {opacity: 1}
}
<h2>Bottom Modal</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

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

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body"><iframe name="myiframe"></iframe>
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

3
  • Создай функцию, которая запускает открытие окна, и потом хоть сотней кнопок запускай эту самую функцию ...
    – Air
    23 ноя 2017 в 18:42
  • Пожалуйста помогите с этой функцией, 23 ноя 2017 в 18:43
  • @Air <button href="bar.html" id="myBtn"target="myiframe">Bar</button> <button href="baz.html" id="myBtn"target="myiframe">Baz</button> например эти кнопки которые должны открывать её, но с помощью функции onClick их запустить у меня не получается(((( 23 ноя 2017 в 18:45

3 ответа 3

4

var modal = document.getElementById('myModal');

var myBtn = document.getElementsByClassName('myBtn');
var close = document.getElementsByClassName('close')[0];
/*
А это в цикле прокруциваем те элементы которыми мы открываем модал окно
и обработчик события который открывет окно
*/
for (var i = 0; i < myBtn.length; i++) {
  myBtn[i].addEventListener('click', function() {
    openModalWindow();
  })
}
// это обработчик события, который в нутри этой функции выполнят ту функцию 
//которая закрывает окно модальное
close.addEventListener('click', function() {
  closeModalWindow();
})

//это функция, которая открывает окно
function openModalWindow() {
  modal.style.display = "block";
}

//это функция, которая закрывает окно
function closeModalWindow() {
  modal.style.display = "none";
}
/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  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 */
  -webkit-animation-name: fadeIn;
  /* Fade in the background */
  -webkit-animation-duration: 0.4s;
  animation-name: fadeIn;
  animation-duration: 0.4s
}


/* Modal Content */

.modal-content {
  position: fixed;
  bottom: 0;
  background-color: #fefefe;
  width: 100%;
  -webkit-animation-name: slideIn;
  -webkit-animation-duration: 0.4s;
  animation-name: slideIn;
  animation-duration: 0.4s
}


/* 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;
}

.modal-header {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}

.modal-body {
  padding: 2px 16px;
}

.modal-footer {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}


/* Add Animation */

@-webkit-keyframes slideIn {
  from {
    bottom: -300px;
    opacity: 0
  }
  to {
    bottom: 0;
    opacity: 1
  }
}

@keyframes slideIn {
  from {
    bottom: -300px;
    opacity: 0
  }
  to {
    bottom: 0;
    opacity: 1
  }
}

@-webkit-keyframes fadeIn {
  from {
    opacity: 0
  }
  to {
    opacity: 1
  }
}

@keyframes fadeIn {
  from {
    opacity: 0
  }
  to {
    opacity: 1
  }
}
<h2>Bottom Modal</h2>

<!-- Trigger/Open The Modal -->

<button id="myBtn-1" class="myBtn">Open Modal-1</button>
<button id="myBtn-2" class="myBtn">Open Modal-2</button>
<button id="myBtn-3" class="myBtn">Open Modal-3</button>

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

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body"><iframe name="myiframe"></iframe>
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

2

В JavaScript:

var btn1 = document.getElementById("myBtn1");
var btn2 = document.getElementById("myBtn2");

function OpenModal() {
     modal.style.display = "block";
}    

btn1.onclick = OpenModal;
btn2.onclick = OpenModal;

HTML:

<button id="myBtn1">Open Modal 1</button>
<button id="myBtn2">Open Modal 2</button>

Остальной код оставить как в вопросе.

0
0

Специально для этого сделал модалку. Вот ссылка.

Внизу нужно кое-что переопределить

new XMC({
bodyID: 'rara',  // id для блока с контентом
backgroundLayerID: 'lusia',  //id для фона
selector: 'data-type', // атрибут у кнопок которые вызывают эту модалку
selectorValue: 'openModalForm', // Значение атрибута
btnId: 'fbgmfClose',
content: 'Привет', // Содержание модалки
classListBg: ['zuzu', 'zaza'], // Классы для wrappera
classListBody: ['zuzu', 'zaza2'], // Классы для блока с содержанием
classListBtn: ['zuzu', 'zaza3'], // Классы для кнопки закрыть
styleBg: {          // Стили врапера. Пишем по js-су
    top: '0',
    left:'0',
    right: '0',
    bottom: '0',
    position: 'fixed',
    background: '#00000090',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: '6'
},
styleBody: {      // Стили блока с контентом. Пишем по js-су
    minWidth: '200px',
    minHeight: '200px',
    background: '#ffffff',
    justifyContent: 'center',
    alignItems: 'center',
},
btnStyle: {   // Стили кнопки закрыть. Пишем по js-су
    width: '40px',
    height: "40px",
    background: '#ffffff',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    top: '5%',
    right: '5%',
    cursor: 'pointer'
}

});

Вообще получилась универсальная вещь)

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.