jQuery:点击DIV本身以外的任何地方关闭DIV? [英] jQuery: Close DIV by clicking anywhere apart from the DIV itself?
本文介绍了jQuery:点击DIV本身以外的任何地方关闭DIV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个div,当点击一个按钮时滑下来,我想在用户时向上滑动div:
I have a div that slides down when a button is clicked, and I would like to slide up the div when a user:
- 点击除DIV内部以外的地方
- 点击div中的关闭按钮。
目前我已经进入了一个阶段,你点击一个类 .panel-tab
的元素 - 它在ID 的面板上向下滑动#面板
...点击它滑动的任何地方....
Currently I've got it to a stage where, you click an element with the class .panel-tab
- it slides down the panel with ID #panel
... click anywhere else it slides up....
这是我的代码到目前为止让DIV打开和关闭:
Here is my code so far to get the DIV to open and close:
<script type="text/javascript">
$(document).ready(function(){
$('.panel-tab').click(function(e) {
$("#panel").stop(true, true).slideToggle("slow");
e.stopPropagation();
});
$("body").click(function () {
$("#panel:visible").stop(true, true).slideUp("slow");
});});
</script>
推荐答案
您可以绑定点击
事件到文档
并检查点击事件是否发生在 div
或任何子项中。如果没有,请关闭它。
You could bind a click
event to the document
and check if the click event happend within that div
or any children. If not, close it.
插件时间!
(function($){
$.fn.outside = function(ename, cb){
return this.each(function(){
var $this = $(this),
self = this;
$(document).bind(ename, function tempo(e){
if(e.target !== self && !$.contains(self, e.target)){
cb.apply(self, [e]);
if(!self.parentNode) $(document.body).unbind(ename, tempo);
}
});
});
};
}(jQuery));
使用情况:
$('.panel-tab').outside('click', function() {
$('#panel').stop(true, true).slideUp('slow');
});
这篇关于jQuery:点击DIV本身以外的任何地方关闭DIV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文