在做前端一些特效时,我们的场景中会经常遇到这种情况,当我点击某一个按钮弹出了一个层时,现在点击空白处或者准确的说点击这个层以外的位置实现层隐藏。
首先我需要知道鼠标点击处是否在这个层上,需要通过计算点击位置的宽和高时候在层宽高的范围之内。
方法:
var elementDiv=$(显示层);
var tempoint = divpanel.offset();//获取层的坐标
//e为当前点击元素(需要document)
if (e.pageX > (tempoint.left + elementDiv.width()) || e.pageX < tempoint.left || e.pageY > (tempoint.top + elementDiv.height()) || e.pageY < tempoint.top)
true为点击处在显示层外。
实现:
function (selector, id, func) {
$(document).unbind("click");//为了避免一些不必要的绑定事件所以绑定前先给document解除click绑定
$(document).bind("click",
function (e) {
var divpanel = $( id);
var tempoint =
divpanel.offset();
if (e.pageX > (tempoint.left +
divpanel.width()) || e.pageX < tempoint.left || e.pageY > (tempoint.top +
divpanel.height()) || e.pageY < tempoint.top) {
if (e.target !=
$(selector)) {
divpanel.hide();
if
(func) {
func();
}
$(document).unbind("click");
}}});}
01-鼠标点击空白处实现层隐藏,布布扣,bubuko.com
原文:http://www.cnblogs.com/ffeng/p/3689237.html