JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://unpkg.com/focus-outside@0.5.0/lib/index.js"></script>
<div id="app">
<span id="button" class="focus-button">
点击按钮显示弹出层
</span>
<div
id="dropdown"
class="focus-popup hide">
点击按钮或popup之外收起 popup
</div>
<iframe src="//baidu.com" frameborder="0">
</iframe>
</div>
SCSS
#app {
position: relative;
.focus-button {
background: #f2f2f2;
}
.focus-popup {
position: absolute;
width: 200px;
height: 300px;
background: #ccc;
}
iframe {
width: 100%;
height: 300px;
margin-top: 30px;
}
.focus-outside {
outline: none;
}
.hide {
visibility: hidden;
}
}
JavaScript
const { bind: focusBind, unbind: focusUnbind } = FocusOutside
const button = document.querySelector('#button')
const dropdown = document.querySelector('#dropdown')
focusBind(button, handleOutside)
focusBind(dropdown, handleOutside)
button.addEventListener('click', () => {
removeClass(dropdown, 'hide')
})
function handleOutside () {
addClass(dropdown, 'hide')
}
function addClass (el, name) {
const classList = el.className.split(' ')
if (classList.indexOf(name) > -1) return
classList.push(name)
el.className = classList.join(' ')
}
function removeClass (el, name) {
const classList = el.className.split(' ')
const index = classList.indexOf(name)
if (index < 0) return
classList.splice(index, 1)
el.className = classList.join(' ')
}