gpt4 book ai didi

jquery - 单击容器外部的窗口时关闭模式 - jQuery

转载 作者:行者123 更新时间:2023-12-01 05:11:45 26 4
gpt4 key购买 nike

我正在练习以下布局,但无法弄清楚目标是什么:

HTML

<button id="opencontact" type="button" name="button">
<i class="far fa-envelope fa-2x"></i>
</button>

<section id="contact-section">
<div class="contact-container">
<div class="contact-content">
<h2>Contact Us</h2>
<label for="">Email</label>
<input type="text" name="" value="">
<label for="">Name</label>
<input type="text" name="" value="">
<label for="">Message</label>
<textarea name="name" rows="8" cols="80"></textarea>
<button type="button" name="button">Submit</button>
</div>
</div>
</section>

CSS:

body {
padding: 0;
margin: 0;
font-family: Helvetica;
box-sizing: border-box;
}

#opencontact {
bottom: 10px;
right: 10px;
position: fixed;
}

#contact-section {
height: 60%;
width: 40%;
position: absolute;
top: 20%;
left: 30%;
display: none;
align-items: center;
justify-content: center;
background-color: red;
}

#contact-section.show {
display: flex;
}

.contact-container {
height: 90%;
width: 90%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}

.contact-content {
height: 90%;
width: 90%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}

还有一个基本的 jQuery 脚本,用于在单击时打开联系人部分:

<script type="text/javascript">

$("#opencontact").click(function() {
$("#contact-section").toggleClass("show");
});

</script>

我要添加什么脚本才能使模式在单击联系部分外部的窗口时关闭?我在网上找到的所有解决方案都不起作用,因此任何提示都会很棒。

最佳答案

首先,您必须为整个网站附加点击监听器。每次点击时,您都会询问您的点击是否包含您想要的元素。不要担心每次点击它都会执行 if 语句,这实际上不是性能问题,这是处理此问题的正确方法。

代码将如下所示(无需使用 jQuery)。您可以查看this snippet .

const contactSection = document.querySelector('#contact-section');
let isContactSectionShowed = false;

window.addEventListener('click', function (e) {
if (e.target === contactSection && !isContactSectionShowed) {
contactSection.classList.add("show");
isContactSectionShowed = true;
} else if (e.target !== contactSection && isContactSectionShowed) {
contactSection.classList.remove("show");
isContactSectionShowed = false;
}
});

关于jquery - 单击容器外部的窗口时关闭模式 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61271739/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com