скрытие меню при клике вне кнопки JQuery
Я не могу понять почему при клике вне dropdown ничего не происходит
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Radio+Canada:wght@600&display=swap" rel="stylesheet">
<style>
li {
list-style: none;
}
.content {
width: 200px;
font-family: 'Radio Canada';
font-size: 30px;
margin: 0 0 0 -40px;
background: rgb(208, 255, 119);
border: 2px solid black;
border-left: none;
border-right: none;
}
.content:hover {
background: rgb(218, 255, 148);
}
.btn {
position: relative;
font-size: 20px;
width: 200px;
height: 50px;
letter-spacing: 5px;
font-family: 'Radio Canada';
text-align: left;
background: rgb(208, 255, 119);
border: 3px solid black;
border-radius: 10px;
transition: 0.5s;
}
.btn.active {
border-radius: 10px 10px 0 0;
}
.btn::before {
content: '';
position: absolute;
width: 20px;
height: 2px;
background: black;
transform: rotate(45deg);
margin: 13px 0 0 150px;
transition: 0.5s;
}
.btn::after {
content: '';
position: absolute;
width: 20px;
height: 2px;
background: black;
transform: rotate(-45deg);
margin: 13px 0 0 27px;
transition: 0.5s;
}
.btn:hover {
background: rgb(214, 255, 139);
}
.btn.active::after {
transform: rotate(45deg);
}
.btn.active::before {
transform: rotate(-45deg);
}
.list {
margin: -16px 0 0 0;
display: none;
position: absolute;
}
.content {
display: block;
}
.content.last {
border-radius: 0 0 10px 10px;
border-bottom: 3px solid black;
border-left: 3px solid black;
border-right: 3px solid black;
}
.content.first {
border-top: 0px solid black;
}
</style>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>dropdown</title>
</head>
<body>
<div><button class='btn'>dropdown</button></div>
<div class="list">
<ul>
<li><button class="content first">menu</button></li>
<li><button class="content">menu</button></li>
<li><button class="content">menu</button></li>
<li><button class="content">menu</button></li>
<li><button class="content last">menu</button></li>
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$('.btn').click(function() {
$('.list').slideToggle(500);
$('.btn, .btn::before, .btn::after').toggleClass('active')
});
let a = $('.btn')
let b = $('.list')
$(document).click(function(e) {
if (!a.is(e.target) && a.has(e.target).lenght === 0 &&
!b.is(e.target) && b.has(e.target).lenght === 0
) {
b.slideUp(500);
a.removeClass('active')
}
});
});
</script>
</body>
</html>
Ответы (2 шт):
Автор решения: homgo
→ Ссылка
Ошибка в строке "$(document).click(function(e) {". Нельзя так писать. Можно писать, к примеру "$(document).on("click",".list",function() {"