我使用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