我有一个隐藏的固定div,如果我点击一个btn就想显示它,如果我点击任何其他地方就关闭它。现在,如果我点击按钮或页面上的任何位置,我可以隐藏div。
对于下面的代码,我达到了我想要的一半。但是,如果我点击绿色框中的任何位置,我想div仍然打开(可见)。任何人都可以建议任何想法帮助我实现这一目标吗
$(function() {
var OPEN = 0; /* Offset to Open */
var CLOSE = -10000; /* Offset to Close */
var t = 0; /* Default time */
var $obtn = $(".obtn-side");
var $cbtn = $(".cbtn-side");
var main = ".main-wrapper";
$obtn.click(function(event) {
event.preventDefault();
var cid = $(this).attr("href"); /* Get the container id */
navEffect(cid, OPEN, 0);
});
$cbtn.click(function(event) {
event.preventDefault();
var cid = $(this).attr("href");
navEffect(cid, CLOSE, 0);
});
$(".side-wrapper").click(function(event) {
navEffect("#side", CLOSE, 0);
});
});
function navEffect(c, o, t) {
var $con = $(c);
$con.animate({
right: o
}, t);
}

.side-wrapper {
position: fixed;
top: 0px;
width: 100%;
height: 100%;
background: black;
right: -1100%;
}
.side-container {
float: right;
background: green;
width: 50%;
height: 100%;
position: relative;
box-shadow: 0px 0px 5px 2px rgba(52, 73, 94, 0.9);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="side" class="side-wrapper">
<div class="side-container">
<a class="cbtn-side" href="#side">x</a>
<div>
<h1>Side bar</h1>
</div>
</div>
</div>
<a class="obtn-side" href="#side">open</a>
&#13;
答案 0 :(得分:1)
如果点击绿色区域.side-container
,您需要停止事件冒泡:
$(".side-container").click(function(e) {
e.stopPropagation();
});
查看下面的演示。
$(function() {
var OPEN = 0; /* Offset to Open */
var CLOSE = -10000; /* Offset to Close */
var t = 0; /* Default time */
var $obtn = $(".obtn-side");
var $cbtn = $(".cbtn-side");
var main = ".main-wrapper";
$obtn.click(function(event) {
event.preventDefault();
var cid = $(this).attr("href"); /* Get the container id */
navEffect(cid, OPEN, 0);
});
$cbtn.click(function(event) {
event.preventDefault();
var cid = $(this).attr("href");
navEffect(cid, CLOSE, 0);
});
$(".side-wrapper").click(function(event) {
navEffect("#side", CLOSE, 0);
});
$(".side-container").click(function(e) {
e.stopPropagation();
});
});
function navEffect(c, o, t) {
var $con = $(c);
$con.animate({
right: o
}, t);
}
.side-wrapper {
position: fixed;
top: 0px;
width: 100%;
height: 100%;
background: black;
right: -1100%;
}
.side-container {
float: right;
background: green;
width: 50%;
height: 100%;
position: relative;
box-shadow: 0px 0px 5px 2px rgba(52, 73, 94, 0.9);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="side" class="side-wrapper">
<div class="side-container">
<a class="cbtn-side" href="#side">x</a>
<div>
<h1>Side bar</h1>
</div>
</div>
</div>
<a class="obtn-side" href="#side">open</a>