2016-03-07 91 views
0

那么,这里有很多解决这类问题的方法。但是,我的问题是我不允许编辑现有的功能。现有的功能是:如何通过点击外部的关闭事件来调用点击函数来关闭展开后的div

$('body').on('click', '.parent.normal', function() { 
    // code for Expanding a div 
}); 

$('body').on('click', '.parent.expand', function() { 
    // code for Closing expanded div 
}); 

什么我能做的就是定义点击展开DIV将调用现有的点击事件结束的div扩大外另一click功能。要做到这一点,我写了这样的:

if($('.parent.expand').length > 0) { 
    $('div:not(".parent.normal, .expanded-content, .expanded-content > div")').click(function() { 
     $('.parent.expand').click(); 
    }); 
    } 

这实际上不起作用。我怎样才能使它工作?

Fiddle Demo

+0

可能的复制[如何检测一个点击的元素之外?](http://stackoverflow.com/questions/152975/how-to-detect-a-click -outside-an-element) – Teemu

回答

1

将此添加到您现有的代码必须解决问题。

$(document).on('click',function(e){ 
    if (!$(e.target).parents('.content').length > 0){ 
    $('.parent.expand').click(); 
    } 
}); 

下面是一个working Fiddle

+0

谢谢,你能告诉我,如果我在你的代码中写$(body).on(...)而不是$(document).on(...),为什么它不起作用? – user1896653

+0

,因为在那个例子中身体高度只能达到展开的div高度,检查元素,你会注意到它。所以从技术上讲,点击不会发生在身体内部,而是发生在外部 –

0

你需要编辑你的CSS,使你的身体有宽度为100%和100%的高度。这将为您的点击事件创建一个区域以在div外注册。

html, body { 
    margin: 0; 
    padding: 0; 
    height: 100%; 
    width: 100%; 
} 

然后用此javascript:

// open expand content 
$('body').on('click', '.parent.normal', function (e) { 
    e.stopPropagation(); 
    e.preventDefault(); 
    $(this).removeClass('normal'); 
    $(this).addClass('expand'); 
    $(this).parent().find('.expanded-content').slideDown(300); 
}); 

// close expand content 
$('body').on('click', '.parent.expand', function (e) { 
    e.stopPropagation(); 
    e.preventDefault(); 
    $(this).removeClass('expand'); 
    $(this).addClass('normal'); 
    $(this).parent().find('.expanded-content').slideUp(300); 
}); 

$('body').on('click', function (e) { 
    e.stopPropagation(); 
    e.preventDefault(); 
    $('.parent.expand').click(); 
}); 

Fiddle demo

+0

感谢您的帮助 – user1896653

1

这将做到这一点而不做任何改变在现有的功能:

$(document).mouseup(function (e) { 

    var elem_not = $(".parent.normal, .parent.expand, .expanded-content, .expanded-content > div"); 

    if (!elem_not.is(e.target) && elem_not.has(e.target).length === 0) { 
     $('.parent.expand').click(); 
    } 

}); 

更新您的FIDDLE

+0

谢谢!这也是一个很好的解决方案 – user1896653