如何使用html,css和jquery创建模态框?

如何使用html,css和jquery创建模态框?

 

    

对于创建模态,它通常需要的不仅仅是HTML,您经常需要使用Javascript。 我为你创造了一个非常小的,以帮助你理解。

CSS用于设置按钮的样式并隐藏元素显示它们不显示,Javascript激活模态的实际function。 您需要做的就是将HTML编辑为您想要的任何内容。

 var modal = document.getElementById('myModal'); // Get the button that opens the modal var btn = document.getElementById("myBtn"); // Get the  element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on  (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"; } } 
 .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 */ } /* Modal Content/Box */ .modal-content { 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; } 
    

对于创建模态,您还可以使用一些库。

其中一个你可以使用w3css库

    
×

Some text. Some text. Some text.

Some text. Some text. Some text.

你为什么不使用JQuery UI Dialog ,它非常方便,如果你仍然想使用jquery这样做,那么你可以尝试下面。

 $('#myBtn').click(function(){ $('.modal-content').show(); $('body').toggleClass('modalbackground'); }); $('.modal-content .close').click(function(){ $('.modal-content').hide(); $('body').toggleClass('modalbackground'); }); 
 .modal-content { display: none; position: fixed; } .modalbackground { width: 100%; height: 100%; background: rgba(0,0,0,0.25); z-index: 1; } .modal-content { width: 33.333%; top: 20%; left: 33.3333%; background: white; z-index: 2; } .close{ cursor: pointer; } 
    

这是一个多模态创建的例子,只需检查出来。

 function createModal(){ var dataModal = ""; var countModal = $(".modalWrap").length; if(typeof countModal === "undefined" || countModal == 0){ countModal = 0; } /*this just an example, you can try improv it more like load file or url to fill your modal data.*/ dataModal = ''; $('body').append(dataModal); } function closeModal(idModal){ $(idModal).remove(); } 
 .modalWrap{ width : 100%; background : rgba(0,0,0,0.5); min-height : 500px; position : fixed; top:0; left:0; } .modalBody{ width : 60%; min-height: 250px; background : #fff; margin-top : 10%; }