У меня есть ссылка для входа и при нажатии на нее отображается div. При нажатии ссылки, я хочу переключиться между скрыть и показать этого div. Также мне нужно скрыть div, как только пользователь нажимает на кнопку вне div.
То, что я сделал, показано ниже:
$(document).ready(function() {
$("#poplink").click(function() {
$('#popup').toggle();
});
$(document).mouseup(function(e) {
var container = $("#popup");
if (!container.is(e.target) && container.has(e.target).length === 0) { // if the target of the click isn't the container...
// ... nor a descendant of the container
container.hide();
}
});
});
Проблема в том, что я не могу переключаться между скрыть и показать. Когда я выхожу за пределы div, он скрывается отлично.
Может ли кто-нибудь помочь мне решить эту проблему. FIDDLE
Зарегистрируйте обработчик клика для документа, а не mouseup
$(document).ready(function () {
$("#poplink").click(function (e) {
e.stopPropagation();
$('#popup').toggle();
$('#regpopup').hide();
});
$(document).click(function (e) {
var container = $("#popup");
if (!container.is(e.target) // if the target of the click isn't the container...
&&
container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
});
Демо: скрипка
Хм, я вижу, где вы скопировали этот бит. Изменил его для вас, так что теперь он работает:
$(document).ready(function()
{
$("#poplink").click(function(e)
{
e.stopPropagation();
$('#popup').toggle();
$('#regpopup').hide();
});
$("*:not(#poplink)").click(function (e) {
var container = $("#popup");
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});
});
И JSFiddle: http://jsfiddle.net/f9Ywh/8/
$('#regpopup').hide();
кажется, не используется, так что избыточно