1 回答
TA贡献1851条经验 获得超5个赞
最简单的解决方法是存储对“新音频”的引用button并检查是否是target单击的document。如果是这样,那么return从函数中不更新DOM.
const button = document.querySelector('button')
button.addEventListener('click', showBox);
// ..
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (event.target === button) return
// ..
请记住,使用您拥有的当前代码,该hideOnClickOutside函数只会在第一次isVisible为 true 而target不是button,因为您在该条件下删除了事件侦听器。
function showBox(e) {
document.body.style.opacity = "0.5";
document.querySelector('div').style.display = "block";
}
const button = document.querySelector('button')
button.addEventListener('click', showBox);
const isVisible = elem => !!elem && !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (event.target === button) return
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none';
removeClickListener()
document.body.style.opacity = "1";
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
hideOnClickOutside(document.querySelector('div'));
<button>New Audio</button>
<div style="display: none">
<button>Record Directly</button>
</div>
另一个问题是,一旦showBox调用该函数,您实际上可能希望在button外部考虑该函数。让我们重构您的代码以存储对showButtonand的引用box,将标志添加到disable并showButton仅在单击时将事件侦听器添加到文档中,showButton并仅在显示框时删除事件侦听器。
您可以稍后对其进行重构以适合您的特定用例。这个想法是考虑这个应用程序可以处于的各种状态并创建函数来管理该状态。
const box = document.querySelector('#box');
const showButton = document.querySelector('#show-button');
showButton.addEventListener('click', showBox);
let isDisabled = false;
const isVisible = elem => !!elem && !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
function toggleDisabled(bool) {
showButton.attributes.disabled = bool;
isDisabled = bool;
}
function toggleDisplay(display, opacity) {
document.body.style.opacity = opacity;
box.style.display = display;
}
function showBox(event) {
if (!isDisabled) {
event.preventDefault();
event.stopPropagation();
toggleDisplay("block", 0.5);
toggleDisabled(true);
document.addEventListener('click', outsideClickListener);
}
}
function outsideClickListener(event) {
if (!box.contains(event.target) && isVisible(box)) { // or use: event.target.closest(selector) === null
toggleDisplay("none", 1);
toggleDisabled(false);
document.removeEventListener('click', outsideClickListener)
}
}
<button id="show-button">New Audio</button>
<div id="box" style="display: none">
<button>Record Directly</button>
</div>
添加回答
举报