单击图标时,我正在为我的产品创建一个弹出窗口。我想这样做,一旦用户点击弹出框外的某个地方,弹出框就会自动消失。目前,弹出窗口关闭和消失的唯一方法是单击使弹出窗口开始显示的同一图标按钮。如果你能帮助我使用我提供的代码,我将不胜感激,因为我是一个初学者,可能无法纳入一般建议,但我当然会尽力!非常感谢你们提前提供的帮助和建议。
HTML弹出代码
<div class="box">
<div class="icons">
<a href="#contact" class="fas fa-shopping-cart"></a>
<div class="popup" onclick="myFunction()">
<span class="popuptext" id="myPopup">RAW Pipe Cleaners are naturally strong and absorbent and wrapped around a flexible banded iron core. These are the natural way to clean your pipe or rig! A RAW Innovation!</span>
<a href="#" class="fas fa-info">
</a></div>
<a href="#" class="fas fa-eye"></a>
</div>
弹出CSS代码
/* Popup container */
.popup {
position: relative;
display: inline-block;
cursor: pointer;
}
/* The actual popup (appears on top) */
.popup .popuptext {
visibility: hidden;
width: 300px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 8px 0;
position: absolute;
z-index: 1;
bottom: -740%;
left: 50%;
margin-left: -150px;
height: 400px;
font-size: 18px;
padding: 50%;
}
/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}
@keyframes fadeIn {
from {opacity: 0;}
to {opacity:1 ;}
}
弹出JS代码
// When the user clicks on <div>, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
我想让它在用户点击弹出框之外的某个地方
您可以捕获点击事件,并检查它是在您的弹出窗口上还是在弹出窗口之外点击的。
// Get the your popup
var popup = document.getElementById("mypopup");
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == popup) {
popup.style.display = "none";
}
}
<div id="mypopup" class="box">
<div class="icons">
<a href="#contact" class="fas fa-shopping-cart"></a>
<div class="popup" onclick="myFunction()">
<span class="popuptext" id="myPopup">RAW Pipe Cleaners are naturally strong and absorbent and wrapped around a flexible banded iron core. These are the natural way to clean your pipe or rig! A RAW Innovation!</span>
<a href="#" class="fas fa-info">
</a></div>
<a href="#" class="fas fa-eye"></a>
</div>
</div>
您可以创建一个新变量,并声明当用户在弹出区域外单击时,它会自动关闭。
window.onclick = function(event) {
if (event.target == popup) {
popup.style.display = "none";
}
}