Как заставить модальное окно работать в этом коде?
Я очень признателен, если вы покажете мне, как заставить модальное окно работать в этом коде. Предполагается, что это "машина котировок". Я намеревался вставить все элементы html dom в ячейки таблицы. Затем с помощью моего массива объектов цитат и с помощью случайных чисел и для циклов, пытающихся сопоставить названия фильмов в самых внешних элементах div, и после щелчка по этому специальному элементу div открывается модальное окно, которое содержит цитату из указанного фильма.
Интересно, происходит ли ошибка из цикла for, что означает, что не все ячейки содержат мои элементы, или я называю элементы неправильно.
ФУНКЦИЯ
function tbl () {
var body = document.getElementsByTagName("body")[0];
var tab = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 10; j++) {
var cell = document.createElement("td");
var domain = document.createElement("div")
domain.setAttribute("id", "frame")
domain.classList.add("popup")
var text = document.createElement("p");
var container = document.createElement("div")
container.setAttribute("id", "myModal")
container.classList.add("modal")
var content = document.createElement("div")
content.classList.add("modalcontent")
var button = document.createElement("span")
button.classList.add("close")
content.appendChild(text)
content.appendChild(button)
container.appendChild(content)
domain.appendChild(container)
cell.appendChild(domain)
row.appendChild(cell)
}
tblBody.appendChild(row);
}
button.innerHTML = "×"
button.setAttribute("id", "myBtn")
tab.appendChild(tblBody);
body.appendChild(tab);
tab.setAttribute("border", "2");
tab.setAttribute("id", "myTable")
document.body.style.backgroundColor = "black";
function win () {
function Quotas (movie, char, quote) {
this.movie = movie;
this.char = char;
this.quote = quote;
}
var Quote_Array = [new Quotas("Apollo 13", "Jim Lovell", "Houston, we have a problem."), new Quotas("Dead Poets Society", "John Keating", "Carpe diem. Seize the day, boys. Make your lives extraordinary."), new Quotas("Star Wars: A New Hope", "Obi-Wan Kenobi", "These are not the droids you're looking for."), new Quotas("The Wizard of Oz", "Dorothy Gale", "There's no place like home."), new Quotas("The Godfather", "Calo", "In Sicily, women are more dangerous than shotguns."), new Quotas("The Godfather", "Sollozzo", "I don't like violence, Tom. I'm a businessman; blood is a big expense."), new Quotas("The Lord of the Rings: The Return of the King", "Gimli", "Certainty of death. Small chance of success. What are we waiting for?"), new Quotas("The Lord of the Rings: The Return of the King", "Witch King", "Do not come between the Nazgul and his prey."), new Quotas("The Lord of the Rings: The Return of the King", "Legolas", "The way is shut. It was made by those who are dead, and the dead keep it. The way is shut."), new Quotas("The Lord of the Rings: The Return of the King", "Galadriel", "This task was appointed to you, Frodo of the Shire. If you do not find a way, no one will."), new Quotas("The Good, the Bad and the Ugly", "Blondie", "You see, in this world there's two kinds of people, my friend: Those with loaded guns and those who dig. You dig."), new Quotas("The Good, the Bad and the Ugly", "Tuco", "I'm looking for the owner of that horse. He's tall, blonde, he smokes a cigar, and he's a pig!"), new Quotas("Star Wars: The Empire Strikes Back", "Yoda", "Control, control, you must learn control!"), new Quotas("Star Wars: The Empire Strikes Back", "Darth Vader", "Luke, you can destroy the Emperor. He has foreseen this. It is your destiny. Join me, and together we can rule the galaxy as father and son.")]
for (var k = 0; k < 5; k++) {
var x = document.getElementById("myTable").rows[k].cells;
for(var l = 0; l < 10; l++) {
var rnd = Math.floor(Math.random() * 14)
x[l].getElementsByTagName("p").innerHTML = rnd
x[l].children[0].innerHTML = Quote_Array[rnd].movie
var mod = domain.getElementsByClassName('modal')[0];
var btn = document.getElementsByClassName("popup")[0]
var span = document.getElementsByClassName("close")[0]
var tape = document.getElementById("myTable").rows[k].cells[l]
tape.onclick = function() {
mod.style.display = "block";
}
span.onclick = function() {
mod.style.display = "none";
}
window.onclick = function(event) {
if (event.target == mod) {
mod.style.display = "none";
}
}
}
}
} win()
};
CSS
<style>
td {
position: relative;
padding: 50px 54px 50px 54px;
border-width: 5px;
overflow: visible;
}
table {
table-layout: fixed;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 100%;
width: 100%;
border-style: outset;
border-color: grey;
z-index: -1;
}
.popup {
position: absolute;
display: block;
cursor: pointer;
color: white;
padding: auto;
vertical-align: middle;
bottom: 25%;
right: 0%;
float: left;
text-align: center;
font-family: "Russo One";
z-index: 2;
}
/* 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: hidden; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modalcontent {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
HTML
<html>
<head>
<title>Quote Machine Pop-up Version</title>
<link href='//fonts.googleapis.com/css?family=Russo One' rel='stylesheet'>
</head>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<body onload="tbl()">
</body>
</div>
</div>
</div>
</hmtl>
1 ответ
Похоже, проблема возникла, когда вы вставляете содержимое предварительного просмотра в отдельные ячейки. Вместо того, чтобы иметь свой собственный контейнер, он добавляет непосредственно к td
элемент, таким образом удаляя все дочерние элементы, который является модальным контейнером.
Сначала вам нужно объявить отдельный элемент для предварительного просмотра, в этом примере я создал preview
панель.
Кроме того, я заметил .modalcontent
имеет белый цвет для своего содержания. Попробуйте изменить это на что-то другое.
Последнее, что нужно сделать, это переделать модальное поведение. Все, что вам нужно, это переместить модальные блоки обратного вызова внутри tape.onclick
функция, поэтому мы имеем правильную ссылку на ячейку для отдельных ячеек.
function tbl() {
var body = document.getElementsByTagName("body")[0];
var tab = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 10; j++) {
var cell = document.createElement("td");
var preview = document.createElement("div");
preview.classList.add("preview")
var domain = document.createElement("div")
domain.setAttribute("id", "frame")
domain.classList.add("popup")
var text = document.createElement("p");
var container = document.createElement("div")
container.setAttribute("id", "myModal")
container.classList.add("modal")
var content = document.createElement("div")
content.classList.add("modalcontent")
var button = document.createElement("span")
button.classList.add("close")
content.appendChild(text)
content.appendChild(button)
container.appendChild(content)
domain.appendChild(preview)
domain.appendChild(container)
cell.appendChild(domain)
row.appendChild(cell)
}
tblBody.appendChild(row);
}
button.innerHTML = "×"
button.setAttribute("id", "myBtn")
tab.appendChild(tblBody);
body.appendChild(tab);
tab.setAttribute("border", "2");
tab.setAttribute("id", "myTable")
document.body.style.backgroundColor = "black";
function win() {
function Quotas(movie, char, quote) {
this.movie = movie;
this.char = char;
this.quote = quote;
}
var Quote_Array = [new Quotas("Apollo 13", "Jim Lovell", "Houston, we have a problem."), new Quotas("Dead Poets Society", "John Keating", "Carpe diem. Seize the day, boys. Make your lives extraordinary."), new Quotas("Star Wars: A New Hope", "Obi-Wan Kenobi", "These are not the droids you're looking for."), new Quotas("The Wizard of Oz", "Dorothy Gale", "There's no place like home."), new Quotas("The Godfather", "Calo", "In Sicily, women are more dangerous than shotguns."), new Quotas("The Godfather", "Sollozzo", "I don't like violence, Tom. I'm a businessman; blood is a big expense."), new Quotas("The Lord of the Rings: The Return of the King", "Gimli", "Certainty of death. Small chance of success. What are we waiting for?"), new Quotas("The Lord of the Rings: The Return of the King", "Witch King", "Do not come between the Nazgul and his prey."), new Quotas("The Lord of the Rings: The Return of the King", "Legolas", "The way is shut. It was made by those who are dead, and the dead keep it. The way is shut."), new Quotas("The Lord of the Rings: The Return of the King", "Galadriel", "This task was appointed to you, Frodo of the Shire. If you do not find a way, no one will."), new Quotas("The Good, the Bad and the Ugly", "Blondie", "You see, in this world there's two kinds of people, my friend: Those with loaded guns and those who dig. You dig."), new Quotas("The Good, the Bad and the Ugly", "Tuco", "I'm looking for the owner of that horse. He's tall, blonde, he smokes a cigar, and he's a pig!"), new Quotas("Star Wars: The Empire Strikes Back", "Yoda", "Control, control, you must learn control!"), new Quotas("Star Wars: The Empire Strikes Back", "Darth Vader", "Luke, you can destroy the Emperor. He has foreseen this. It is your destiny. Join me, and together we can rule the galaxy as father and son.")]
for (var k = 0; k < 5; k++) {
var x = document.getElementById("myTable").rows[k].cells;
for (var l = 0; l < 10; l++) {
var rnd = Math.floor(Math.random() * 14)
x[l].querySelectorAll(".preview")[0].innerHTML = Quote_Array[rnd].movie;
x[l].querySelectorAll(".modalcontent > p")[0].innerHTML = Quote_Array[rnd].quote;
var tape = document.getElementById("myTable").rows[k].cells[l];
tape.onclick = function() {
var mod = this.getElementsByClassName('modal')[0];
var btn = this.getElementsByClassName("popup")[0];
var span = this.getElementsByClassName("close")[0];
this.style.zIndex = 10;
mod.style.display = "block";
span.onclick = function() {
mod.style.display = "none";
}
window.onclick = function(event) {
if (event.target == mod) {
tape.style.zIndex = 1;
mod.style.display = "none";
}
}
}
}
}
}
win()
};
td {
position: relative;
padding: 50px 54px 50px 54px;
border-width: 5px;
overflow: visible;
}
table {
table-layout: fixed;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 100%;
width: 100%;
border-style: outset;
border-color: grey;
z-index: -1;
}
.popup {
position: absolute;
display: block;
cursor: pointer;
color: white;
padding: auto;
vertical-align: middle;
bottom: 25%;
right: 0%;
float: left;
text-align: center;
font-family: "Russo One";
z-index: 2;
}
/* 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: hidden;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content/Box */
.modalcontent {
background-color: #fefefe;
margin: 15% auto;
/* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%;
color: #000000;
/* Could be more or less, depending on screen size */
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<html>
<head>
<title>Quote Machine Pop-up Version</title>
<link href='//fonts.googleapis.com/css?family=Russo One' rel='stylesheet'>
</head>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<body onload="tbl()">
</body>
</div>
</div>
</div>
</html>