Javascript 在 div 外单击后删除类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26672241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove class after click outside the div
提问by Arun P Johny
I know this is a old question , but i've searched a lot .
i want to remove class after clicked outside the like body . here is my code :
Html
我知道这是一个老问题,但我已经搜索了很多。我想在像身体之外点击后删除课程。这是我的代码:
Html
<div id="user-login-top">Enter</div>
<div id="user-login-wrapper" class="">visible</div>
Jquery
查询
$(function () {
$("#user-login-top").on("click", function () {
$("#user-login-wrapper").addClass("wide");
});
$(document).on("click", function (e) {
if ($(e.target).is("#user-login-wrapper") === false) {
$("#user-login-wrapper").removeClass("wide");
}
});
});
and here is the fiddle : Fiddle
这是小提琴:小提琴
Appreciate your help !?
Thx
感谢你的帮助 !?
谢谢
回答by Arun P Johny
It is because of the propagation of event.
这是因为事件的传播。
When you click on user-login-top, the first click handle is triggered which is adding the class, then because of event propagation the handler attached to the document is triggered where it satisfies the if condition and removes the class.
当您单击 时user-login-top,将触发第一个单击句柄,即添加类,然后由于事件传播,附加到文档的处理程序在满足 if 条件时被触发并删除类。
One possible solution here is to use event.stopPropagation()
一种可能的解决方案是使用event.stopPropagation()
$(function() {
$("#user-login-top").on("click", function(e) {
$("#user-login-wrapper").addClass("wide");
e.stopPropagation()
});
$(document).on("click", function(e) {
if ($(e.target).is("#user-login-wrapper") === false) {
$("#user-login-wrapper").removeClass("wide");
}
});
});
#user-login-wrapper {
opacity: 0;
}
#user-login-wrapper.wide {
opacity: 1 !important;
}
<div id="user-login-top">????</div>
<div id="user-login-wrapper" class="">visible</div>
Another is
另一个是
$(function() {
$("#user-login-top").on("click", function(e) {
$("#user-login-wrapper").toggleClass("wide");
});
$(document).on("click", function(e) {
if ($(e.target).is("#user-login-wrapper, #user-login-top") === false) {
$("#user-login-wrapper").removeClass("wide");
}
});
});
#user-login-wrapper {
opacity: 0;
}
#user-login-wrapper.wide {
opacity: 1 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="user-login-top">????</div>
<div id="user-login-wrapper" class="">visible</div>

