как добавить несколько модальных блоков - PullRequest
0 голосов
/ 06 августа 2020

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

// just to pretty up the box and add come color

const box = document.querySelector(".box");
box.style.display = "none";
const header = document.querySelector(".header");
const close = document.querySelector("#box-close");
const open = document.querySelector(".button");


close.addEventListener("click", closeBox);
open.addEventListener("click", openBox);
header.addEventListener("mousedown", mouseDown);


function mouseDown(i){

    
    window.addEventListener("mousemove", drag);  // it listens to see if the mouse is clicking down on the div, when it does, it calls the function"drag"
    window.addEventListener("mouseup", letGo);   // it listens to see if the mosue isn't clicking anymore, when it does, it calls the function "letGo"

    var windowHeight = window.innerHeight;
    var windowWidth =window.innerWidth;
    let previousX = i.clientX;                   //make a variable called previousX that stores the data of your current mouse X position
    let previousY = i.clientY;                   //make a variable called previousY that stores the data of your current mouse Y postion

    function drag(i){                            //what happens when the program detects a mouse click
        let currentX = previousX - i.clientX;      // make s a variable called currentX that stores the x distance that your mouse traveled
        let curretY = previousY - i.clientY;       //makes a variable called currentY that stores the Y distance that your mouse traveled
        const bounds = box.getBoundingClientRect();   // gets the boundaries of the box object and their postions on the browser windows

        if(bounds.left <= 0 ){                                //if the left bound of the box is touching the left side of the screen 
            box.style.top = bounds.top - curretY + "px";      //allow for the updating in the y direction
            box.style.left = bounds.left + 5 +"px";           //bounce off the box 5 pixels to the left
            previousY = i.clientY;                          //reset the y value to allow up and down movement
            console.log("left");
        }
        else if(bounds.right >= windowWidth){                      //does the same thing as the last if statement but if the right bound of the box is touching the right side of the scrren
            box.style.top = bounds.top - curretY +"px";
            box.style.left = bounds.left - 5 +"px";
            previousY = i.clientY;
            console.log("right");
        }
        else if(bounds.bottom >= windowHeight){                       //same thing as the last but if the box touches the bottom
            box.style.left = bounds.left - currentX + "px";
            box.style.top = bounds.top - 5 + "px";
            previousX = i.clientX;
            console.log("down");
        }
        else if(bounds.top <= 0){                                 //same thign as the last but if the box touches the top
            box.style.left = bounds.left - currentX + "px"; 
            box.style.top = bounds.top+  5 + "px";
            previousX = i.clientX;
            console.log("up");
        }
        else{                                               //else if 
            box.style.left = bounds.left - currentX + "px"; //takes the value of the left side of the box and subtracts the difference in distance in pixels
            box.style.top = bounds.top - curretY + "px";    //does the same as the previous line but for the Y/top of the box
            previousX = i.clientX;   //these two lines reset the values of previous x&y so that your current mouse positon is always updating
            previousY = i.clientY;
        }
    }
    function letGo(){                                       // whe the mouse it let go
        window.removeEventListener("mousemove", drag);      //stop listening to the mouse positions so the window doesnt stick to your mouse
        window.removeEventListener("mouseDown", letGo);
    }
}
function openBox(){
    if (box.style.display === "none") {
        box.style.display = "block";
    }
    console.log("open");
}
function closeBox(){
    if(box.style.display !== "none"){
        box.style.display = "none";
    }
    console.log("close");
}
body{
    background-color: gray;
    overflow: hidden;
}
.box{
    font-family: "Comic Sans MS", cursive, sans-serif;
    font-size: 12px;
    border: 1px solid #000;
    position: absolute;
    height: 280px;
    width: 400px;
    background-color: #666;
    z-index: 9;  
}
.header{
    position: relative;
    height: 32px;
    background: rgb(69, 161, 211);
    line-height: 32px;
    font-size: 1.2em;
    vertical-align: middle;
    padding: 0 8px 0 8px;
    white-space: normal;
    overflow: hidden;      
    cursor: move;  
}
.box-buttons{
    position: absolute;
    display: flex;
    flex-direction: row-reverse;
    right: 0em;
    top: 0em;
}
.operation-button{
    height: 32px;
    width: 32px;
    text-align: center;
}
.content{
    position: absolute;
    width: 400px;
    height: 248px;
}
<head>
    <link rel="stylesheet" href="f*$#.css">
</head>
<body>
    <button id="buttonone" class="button">click me</button>
    <div id="boxone" class="box">
        <div class="header">header
            <div class="box-buttons">
                <div id="box-close" class="operation-button">&times</div>
                <div id="box-maximize" class="operation-button">max</div>
                <div id="box-minimize" class="operation-button">min</div>
            </div>
        </div>
        <div class="content">
            content
        </div>
        <div class="resize"></div>
    </div>
    <script src="fuck.js"></script>
</body>
</html>

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

1 Ответ

0 голосов
/ 06 августа 2020

Если вы хотите использовать несколько всплывающих окон, вам придется подойти к проблеме иначе. Вы хотите иметь возможность вызывать метод объекта, который создает новый экземпляр всплывающего окна, чтобы у вас было бесконечное количество доступных кончиков пальцев для вызова, когда они вам понадобятся. Вот почему я предлагаю вам создать конструктор (представьте его как схему) под названием Pop-up, который вы можете вызвать в любое время для создания нового экземпляра всплывающего окна. Затем вы можете использовать метод setContent для передачи любого контента, который вы хотите, в фактическом модальном всплывающем окне. Я подготовил код, показывающий, как это сделать:

https://codepen.io/klaurtar/pen/YzqzKRK

Вот HTML:

<button id="pop-up">Button</button>

Здесь это какой-то базовый c css:

html, body {
  height: 100%;
  width: 100%;
}



.pop-up {
  position: fixed;
  height: 300px;
  width: 300px;
  background-color: grey;
  
/*  Positioning  */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.body {
  height: 100%;
  width: 100%;
}

.exit-button {
  cursor: pointer;
}

Каждый раз, когда нажимается кнопка, создается новый экземпляр всплывающего окна в JavaScript.

  const button = document.body.querySelector('#pop-up');

button.addEventListener('click', () => {
  const popup = popUpManager.createPopUp();
  
  popup.setContent('<h1>Hello from the popup!</h1>');
})

const popUpManager = (function popUpManager() {
  const $popUpManager = document.createElement('div');
  $popUpManager.className = "pop-up_manager";
  
  document.body.append($popUpManager);
  
  return {
    createPopUp: () => {
      const popup = new Popup();
      const $popup = popup.getPopup();
      $popUpManager.append($popup);
      return popup;
    }
  }
})();

class Popup{
  constructor() {
    this.$popup = document.createElement('div');
    this.$popup.className = 'pop-up';
    this.$popup.innerHTML = '<div class="exit-button">X</div><div class="body"></div>';
    
    this.$exitButton = this.$popup.querySelector('.exit-button');
    this.$body = this.$popup.querySelector('.body');
    
    this.setUpListeners();
  }
  
  getPopup() {
    return this.$popup;
  }
  
  setContent($content) {
    if (typeof $content === 'string') {
      this.$body.innerHTML = $content;
    } else {
      this.$body.appendChild($content);
    }
  }
  
  close() {
    this.$popup.remove();
  }
  
  setUpListeners() {
    this.$exitButton.addEventListener('click', () => {
      this.close();
    });
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...