【发布时间】:2017-10-06 09:16:52
【问题描述】:
尝试创建一个在将鼠标悬停在元素上时将显示的弹出窗口。但是,当我在元素内移动鼠标时,它会闪烁并四处移动。如果鼠标移到弹出窗口上,它也应该保持打开状态。 尝试在没有像 jQuery 这样的库作弊的情况下做到这一点。如果你使用它们,你就不会学习。
如果您将鼠标悬停在以下标签之一上,这正是我想要创建的。
认为错误出在这段代码中:
function showPopup(e) {
var popup = document.getElementById('popup');
if (popup.style.display == 'none') {
popup.style.display = 'block';
var bodyRect = document.body.getBoundingClientRect(),
elemRect = e.target.getBoundingClientRect(),
offsetX = elemRect.left - bodyRect.left,
offsetY = elemRect.bottom - bodyRect.top;
popup.style.left = offsetX + 'px';
popup.style.top = offsetY + 'px';
//console.log(e);
}
}
function hidePopup(/*e*/) {
setTimeout(function() {
var popup = document.getElementById('popup');
if (popup.style.display == 'block' && !window.inside_popup) {
popup.style.display = 'none';
window.inside_popup = false;
console.log('hide');
} else {
setTimeout(hidePopup, 50); // try a little later
}
}, 50); // Give the events ability to catch up and tell us the mouse is inside the popup
}
var targ = document.querySelector('ul li')
targ.addEventListener('mouseover', showPopup);
targ.addEventListener('mouseout', hidePopup);
带有真实测试元素的完整 javascript 代码: https://jsfiddle.net/g8wvae8o/
【问题讨论】:
-
你需要使用mouseenter和mouseleave
标签: javascript html css