最佳答案
您可以通过少量 JS、CSS 和 HTML 的组合来完成此任务
var button = document.getElementById('test-button');
var handleClick = function(e) {
var existingTooltip = document.getElementById('popup-tooltip');
if (existingTooltip) document.body.removeChild(existingTooltip);
var buttonPosition = this.getBoundingClientRect(),
bodyRect = document.body.getBoundingClientRect(),
popup = document.createElement('div'),
coords = {
pageX: buttonPosition.left + (buttonPosition.width / 2),
pageY: (buttonPosition.top - bodyRect.top) + (buttonPosition.height / 2)
};
popup.id = 'popup-tooltip';
popup.classList.add('popup');
document.body.appendChild(popup);
popup.style.left = coords.pageX + 'px';
popup.style.top = coords.pageY + 'px';
}
button.addEventListener('click', handleClick)
button {
margin-left: 200px;
}
.popup {
position: absolute;
z-index: 10;
height: 80px;
background: #fff;
width: 150px;
transform: translate(-50%, 30px);
box-shadow: 0 1px 3px 0 #666
}
.popup:before,
.popup:after {
content: '';
width: 0;
height: 0;
border-left: 15px solid transparent;
border-right: 15px solid transparent;
border-bottom: 10px solid #ccc;
position: absolute;
left: 50%;
top: -1px;
transform: translate(-50%, -100%);
}
.popup:after {
top: 0;
border-bottom: 10px solid #fff;
}
<button type="button" id="test-button">Test</button>
关于javascript - 如何在单击事件发生的确切位置获得弹出的工具提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39594356/