Самый простой способ использовать div в качестве модального диалога с jQuery - PullRequest
0 голосов
/ 27 июня 2019

Я хочу показать содержимое div в виде модального диалога с использованием jQuery.

Есть ли способ сделать это без использования Bootstrap или чего-то еще ...?

Я хочу персонализировать свой модальный диалог по-своему через CSS.

Пожалуйста, покажи мне путь ...

1 Ответ

1 голос
/ 27 июня 2019

Для модального диалогового окна «сверните свое собственное» все, что вам нужно, это два элемента div:

  1. Наложение - находится поверх содержимого вашей страницы (мы используем z-index длявыполните это)

  2. Диалог - находится поверх наложенного элемента div

Вот базовый пример кода.

$('#mybutt').click(function(){
    $('#myOverlay').show();
    $('#myModal').show();
});

$('#shutme, #myOverlay').click(function(){
    $('#myModal').hide();
    $('#myOverlay').hide();
});
#content{background:wheat;}
#myOverlay{position:fixed;top:0;left:0;height:100%;width:100%;background:black;opacity:0.7;display:none;z-index:1;}
#myModal{position:fixed;top:10%;left:10%;border:3px solid darkcyan;display:none;z-index:2;}
#shutme{position:absolute;right:20px;bottom:20px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<button id="mybutt">Show Modal</button>
<div id="myOverlay"></div>
<div id="myModal">
    <img src="http://placekitten.com/450/325" />
    <input type="button" id="shutme" value="Close" />
</div>
<div id="content">
    This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. This is a bunch of content. 
</div>

jsFiddle Demo


Важные примечания:

  1. z-index не работает с элементами, которые используют по умолчанию значение позиции CSS (position:static).Если вам не нужен элемент absolute или fixed, установите его на position:relative (что практически совпадает со значением по умолчанию static, но также поддерживает z-index).

  2. position снова важен для структуры HTML самого диалогового окна.Снова измените его со значения по умолчанию position:static.Значение позиции fixed поместит его в фиксированное положение на экране , тогда как absolute позволит вам разместить его в любом месте первого родительского элемента, который не имеетposition значение static (вы можете видеть, что надоедливое значение position:static проблематично - удивительно, почему оно было выбрано по умолчанию.

  3. Разделительный элементнастроен с помощью z-index, чтобы он находился на верхней части веб-страницы. Мы делаем это по двум причинам: (1) для визуального оформления диалогового окна и (2) для предотвращения взаимодействия пользователя со страницей додиалоговое окно закрыто. (Помните: position:absolute или position:fixed) Приятный эффект - сделать этот div полупрозрачным, используя свойство CSS opacity.

  4. Диалоговое окно div настроено с помощью z-index, чтобы оно располагалось поверх оверлея. Не помещайте диалоговое окно div внутри оверлейного блока. Вы можете сделать это, но это немного сложнее - сделать этопервым делом, а затем поэкспериментируйте с другими возможностями.

  5. Удобно размещать структуры наложения и диалоговых элементов div либо в самом верху тела, либо в самом низу.НЕ размещайте их в контейнерах.Если вы используете Bootstrap, вы можете использовать этот метод, но вам не нужно, так как Bootstrap имеет собственную модальную диалоговую структуру , которая делает его немного прощенастроить супер-крутой модальный диалог.Если вы внимательно посмотрите на их HTML, вы увидите, что это действительно та же самая концепция, которую мы используем здесь - она ​​просто делает больше.

  6. Вам не нужен отдельный модал для каждогосообщение.Довольно просто поменять информацию внутри и из модальной диалоговой структуры.См. этот ответ для большего количества идей и демонстраций.

На самом деле, это ключевая идея, поэтому вот еще один пример, который показывает, как просто это сделать:

$('[id^=mybutt]').click(function(){
    //above selector traps clicks on els where: id "starts with" mybutt
    let btnID = $(this).attr('id');
    let mdlNo = btnID.split('_')[1];
    $('#content_num').val(mdlNo); //Store so can put the data back when done
    //below line MOVES data from numbered storage div into the modal for display
    $('#content_mdl' + mdlNo + ' .mdl_content').appendTo( $('#myMdlInner') );
    $('#myOverlay').show();
    $('#myModal').show();
});

$('#shutme, #myOverlay').click(function(){
    $('#myModal').hide();
    $('#myOverlay').hide();
    let mdlNo = $('#content_num').val(); //get the stored mdl_data number
    //below line MOVES the dialog contents back to the appropriate storage div
    $('#myMdlInner .mdl_content').appendTo( $('#content_mdl' + mdlNo) );
});
#myOverlay{position:fixed;top:0;left:0;height:100%;width:100%;background:black;opacity:0.7;display:none;z-index:1;}

#myModal{position:fixed;top:10%;left:10%;width:70%;height:60%;border:3px solid darkcyan;overflow:hidden;display:none;z-index:2;}
  .mdl_content{height:100%;width:100%;background:white;}

#shutme{position:absolute;right:20px;bottom:20px;}

.flex-parent{display:flex;justify-content:center;align-items:center;}
.mdl_data{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<h1>This demo re-uses one modal dialog for multiple content</h1>
<div id="myOverlay"></div>
<div id="myModal">
    <div id="myMdlInner"></div>
    <input type="button" id="shutme" value="Close" />
    <input type="hidden" id="content_num" />
</div>

<!-- Hidden divs containing content for the modal dialog -->
<div id="content_mdl1" class="mdl_data">
  <div class="mdl_content">
    <img src="http://placekitten.com/450/325" />
  </div><!-- .mdl_content -->
</div><!-- #content_mdl1 -->

<div id="content_mdl2" class="mdl_data">
  <div class="mdl_content">
    <div class="flex-parent">
        <div class="fleft">Some text goes here. Some text goes here. Some text goes here. </div>
        <div class="fright">
            <img src="http://placekitten.com/200/150" />
        </div>
    </div>
  </div><!-- .md2_content -->
</div><!-- #content_mdl2 -->

<button id="mybutt_1">Show Modal 1</button>
<button id="mybutt_2">Show Modal 2</button>

jsFiddle Demo

...