这是我目前所拥有的: 例如,当我点击button1时,content1显示,当我点击button2时,content1关闭,content2出现。 到目前为止,这段代码有效:
$("#buttons a").click(function(e){
e.preventDefault();
var toShow = $(this).attr('href');
$(".togg").fadeOut();
$(toShow).fadeIn();
});
JSFiddle 我想做的是保留这个功能,但添加一些东西:如果 content1 已经打开,当我点击它的按钮 (button1) 时切换它,并且当在 content1 div 之外点击时也切换它。简而言之,我想在单击 div 本身以外的任何地方时切换它。
最佳答案
因为你想检查点击是在元素上还是在元素外,为此你需要检查 nodeName
或 tagName
或 id
$(document).click(function(e) {
//Check the element is none of the DIVS which we wants prevent.
if(e.target.id != "content1" && e.target.id != "content2" && e.target.id != "content3")
{
//Hide the content div which is visible now.
$('div.togg:visible').hide();
}
});
你只需要创建一个动态选择器来实现某种动态切换功能。
$("#buttons a").click(function(e){
var selector = $('.'+$(this).attr('id'));
selector.toggle();
$('div.togg').not(selector).hide();
});
$("#buttons a").click(function(e){
var selector = $('.'+$(this).attr('id'));
selector.toggle();
$('div.togg').not(selector).hide();
});
$(document).click(function(e) {
//Check the element is none of the DIVS which we wants prevent.
if(e.target.id != "content1" && e.target.id != "content2" && e.target.id != "content3")
{
//Hide the content div which is visible now.
$('div.togg:visible').hide();
}
});
.content1 {display:none;}
.content2 {display:none;}
.content3 {display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons">
<a href="#" id="content1">Div 1</a>
<a href="#" id="content2">Div 2</a>
<a href="#" id="content3">Div 3</a>
</div>
<div>
<div class="content1 togg">1111</div>
<div class="content2 togg">2222</div>
<div class="content3 togg">3333</div>
</div>
关于jquery - 单击显示/隐藏 div,在 div 外部单击时切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39687453/