我使用jQuery的功能jQuery的显示隐藏功能
function ShowHide(){
$(".login").animate({"height": "toggle"}, { duration: 1000 });
}
和链接显示隐藏的DIV的.login是:
onclick="ShowHide(); return false;"
但这仅链接切换股利显示和隐藏,但我希望它也可以在用户点击div时隐藏,我有一个页面包装器,但只需要一些jQuery的帮助。
我使用jQuery的功能jQuery的显示隐藏功能
function ShowHide(){
$(".login").animate({"height": "toggle"}, { duration: 1000 });
}
和链接显示隐藏的DIV的.login是:
onclick="ShowHide(); return false;"
但这仅链接切换股利显示和隐藏,但我希望它也可以在用户点击div时隐藏,我有一个页面包装器,但只需要一些jQuery的帮助。
如果您希望用户单击其他任何地方来隐藏它,则需要将事件放在body元素上以隐藏它。
ps:请不要在html元素中使用onclick! - 使用事件管理器中的jQuery为(如某物的addEvent的线(点击,功能))
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<style>
.login-div { width: 100px; height: 100px; margin:auto; border: solid 1px black; position: relative; background-color: #aeaeae; display:none;}
.parent-div { width: 300px; height: 300px; margin:auto; border: solid 1px #aeaeae; position: relative;}
.footer { margin-bottom: 0px; margin-top:auto; margin-left:auto; margin-right:auto; height:40px; width:200px; position:relative; display:none;}
</style>
<script>
$(window).load(function(){
var DEBUG = 0;
var count = 0;
$('.parent-div').bind('click', function(e){
e.preventDefault();
e.stopPropagation();
DEBUG==1?console.log('Target: '+$(e.target).attr('class')):'';
DEBUG==1?console.log('Show Hide: '+(count++)):'';
//ShowHide();
var target_class = $(e.target).attr('class');
if(target_class == 'link'){
$(".login-div").animate({"height": "toggle"}, { duration: 1000 });
$('.footer').toggle();
}
else{
$(".login-div").animate({"height": "hide"}, { duration: 1000 });
$('.footer').hide();
}
});
});
</script>
</head>
<body>
<div class="parent-div">Parent Box:<br/>
<a href="#" class="link">ShowHide</a>
<div class="login-div">Child Box:</div>
<div class="footer">click out side the gray box & inside the Parent-box
</div>
</body>
</html>
我七拼八凑了上述基于我的你的需求理解,退房代码。这应该做你的工作。在这里,我使用java脚本中的“单击”事件冒泡并将事件监听器绑定到parent-div
类元素。如果要增加元素的范围,则可以附加<body/>
。
如果您使用的是Firebug&FF,您可以设置DEBUG = 1 – Ajaxe 2009-10-25 14:58:12
事件如果页面上有多个onclick事件并在页面上附加onclick事件,则事件冒泡和传播变得复杂,但该示例应该可以帮助您。 – dusoft 2009-10-25 15:00:55
我同意dusoft,在DOM上更高会导致对'body'上的'click'处理程序的更多调用,也可能是其中一个子元素'bubbling'链中的某处'event.stopPropagation()',其中所需的处理程序永远不会被调用,并且DIV不会隐藏/显示。事件处理链必须考虑。 – Ajaxe 2009-10-25 16:18:49
更容易
而不是建立一个特定的div点击隐藏元素, 你可以简单地建立在单击时不属于“告诉我”元素,以隐藏部分的所有元素上。
我的意思,在你的JavaScript部分例子,在你准备代码的地方如下:
$("body *").not('.login, .login *').fadeOut(1000);
// This tells jquery to get all elements, in the body, not containing the
// class login or any subelement of it
// The fade out is just a simple jquery hide animation set to 1 second in this
// example but you can hide it however you want
,看看它是如何工作的你。
您能否为此提供一个示例标记? – chris 2009-10-25 10:53:51
你想要的东西像$('#myLink')。click(ShowHide); – 2009-10-25 10:56:43
我appologise,因为我是非常新的jquery,并在初学者阶段,我明白在html中使用onlick是不好的做法,并会真正感激它,如果你能告诉我一个最佳实践方法的例子,非常感谢 – chris 2009-10-25 10:57:58