我已经适用于一个按钮上的点击事件,并显示div.Also我已应用onclick事件身体标记来隐藏该div.But当我点击然后在按钮调用和div显示的单击功能中的按钮。同时onclick身体呼叫和div隐藏事件。隐藏一个div当点击身体,并显示它,当点击一个按钮
我想在点击按钮时显示div,并在点击任何其他位置时隐藏它。
谁能帮我 由于提前
我已经适用于一个按钮上的点击事件,并显示div.Also我已应用onclick事件身体标记来隐藏该div.But当我点击然后在按钮调用和div显示的单击功能中的按钮。同时onclick身体呼叫和div隐藏事件。隐藏一个div当点击身体,并显示它,当点击一个按钮
我想在点击按钮时显示div,并在点击任何其他位置时隐藏它。
谁能帮我 由于提前
只是一个简单的例子。未经测试。除非你提供更多的信息,否则不能多提供。
HTML:
<body>
<div id="element">Show/hide this</div>
<div id="button">Click me!</div>
</body>
JS:
$(document).ready(function() {
// Click event on body hide the element
$("body").click(function() {
$("#element").hide("fast");
});
// Click event on button show the element
$("#button").click(function() {
$("#element").show("fast");
event.stopPropagation();
});
}
按artwl的答案,你会想用event.stopPropagation()
防止事件冒泡DOM树。
你可以试试下面的东西 -
$('body.aClass').click(function(){
$('#divId').hide();
$(this).removeClass('aClass');
});
$('button').click(function(){
$('#divId').show();
$('body').addClass('aClass');
});
$(function(){
$("body").click(function(){
$("#divID").hide();
});
$("#btnShow").click(function(event){
$("#divID").show();
event.stopPropagation();
});
})
使用event.stopPropagation()来阻止事件冒泡DOM树,阻止任何父处理程序被通知的事件。
jQuery的
$('button').click(function(){
alert('show');
$('div').show();
event.stopPropagation(); // <<<<<<<<
});
$('body').click(function(){
$('div').hide();
alert('hide');
})
感谢您的帮助。它的工作 – 2012-07-24 13:17:19
在这里,我已经做了完整的垃圾箱上面的问题。
DEMO:http://codebins.com/bin/4ldqp9s
每当你使用的语句event.stopPropagation();在jquery函数中,那么你必须定义事件变量作为函数参数,那么它将被视为事件对象变量,它工作正常。
HTML:
<div id="panel">
<div id="box">
Div To be Hide/Show
</div>
<br/>
<input type="button" id="btn1" name="btn1" value="Show Div"/>
</div>
CSS:
#box{
height:50px;
width:200px;
background:#55a1dc;
vertical-align:middle;
text-align:center;
border:1px solid #334499;
display:none;
}
JQuery的:
$(document).ready(function() {
// Click event on body hide the element
$("body").click(function(event) {
$("#box").hide(600);
event.stopPropagation();
});
// Click event on button show the element
$("#btn1").click(function(event) {
$("#box").show(600);
event.stopPropagation();
});
});
<script>
$(document).ready(function(){
$("body").click(function(){
$("#effect").hide();
});
$("#button").click(function(){
$("#effect").toggle();
event.stopPropagation();
});
$("#effect").hide();
});
</script>
u能表明乌尔HTML – 2012-07-24 09:40:28