1.做到点击按钮开启浮层
$("#favorite").on('click', function() {
$("#popover").show()
})
2.做到点击按钮开启浮层,再次点击关闭浮层
$("#favorite").on('click', function() {
if (popover.style.display == 'block') {
$("#popover").hide()
} else {
$("#popover").show()
}
})
3.做到点击别处关闭浮层
function listenToDocument() {
$(document).on('click', function(e) {
if (e.target === $('html')[0]) {
$popover.hide()
// 只在浮层出现时监听,节约资源
$(document).off('click', arguments.callee)
}
})
}
4.最终做到
-点击按钮弹出浮层
-点击别处关闭浮层
-点击浮层时,浮层不得关闭
-再次点击按钮,浮层消失点击按钮弹出浮层
最终代码
let $favorite = $("#favorite")
let $popover = $("#popover")
$favorite.on('click', function(e) {
if (popover.style.display == 'block') {
$popover.hide()
} else {
$popover.show()
listenToDocument()
}
})
function listenToDocument() {
$(document).on('click', function(e) {
if (e.target === $('html')[0]) {
$popover.hide()
// 只在浮层出现时监听,节约资源
$(document).off('click', arguments.callee)
}
})
}
以下为HTML
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="navbar">
<button id="favorite">
收藏夹
</button>
<div id="popover" class="popover">
<ul>
<li>百度一下</li>
<li>谷歌一下</li>
<li>Bing一下</li>
</ul>
</div>
</div>
</body>
</html>
css
* {
margin: 0;
padding: 0;
}
.navbar {
position: relative;
display: inline-block;
left: 100px;
top: 100px;
}
.popover {
position: absolute;
border: 1px solid black;
left: 0;
top: 100%;
white-space: nowrap;
display: none;
}
ul li {
list-style-type: none;
margin: 5px;
}
li:hover {
background-color: #e5dbdb;
}
网友评论