我想根据用户在 CircleSVG 中的鼠标位置(单击时)或将其移动到 SVG 的确切中心(同时移动弹出内容和箭头)。是否可以动态更改它?
const popover = new bootstrap.Popover(document.getElementById("test"), {
html: true,
sanitize: false,
trigger: 'manual',
content: 'Nice'
});
function togglePopover() {
popover.toggle();
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<svg onclick="togglePopover()" height="100" width="100">
<circle id="test" cx="50" cy="50" r="40" stroke="black" stroke width="3" fill="red" />
</svg>
最佳答案
是的,可以根据鼠标位置更改弹出窗口的位置。您可以通过附加 <style>
来做到这一点每次单击 SVG 并显示弹出窗口时,使用动态 CSS 将元素添加到 HTML 文档中。
const popover = new bootstrap.Popover(document.getElementById("test"), {
html: true,
sanitize: false,
trigger: 'manual',
content: 'Nice'
});
function addStyle(css) {
const existingStyleElement = document.querySelector('#popoverCustomStyle');
if (existingStyleElement) {
existingStyleElement.remove();
}
document.head.insertAdjacentHTML('beforeend', `
<style id="popoverCustomStyle">${css}</style>
`);
}
document.querySelector('#mySVG').addEventListener('click', function togglePopover(e) {
popover.toggle();
if (popover._hoverState) {
const popoverArrowWidth = popover.tip.querySelector('.popover-arrow').getBoundingClientRect().width;
const popoverPlacementSettings = {
left: {
x: `calc(${e.pageX - popoverArrowWidth}px - 100%)`,
y: `calc(${e.pageY}px - 50%)`
},
right: {
x: `${e.pageX + popoverArrowWidth}px`,
y: `calc(${e.pageY}px - 50%)`
},
top: {
x: `calc(${e.pageX}px - 50%)`,
y: `calc(${e.pageY - popoverArrowWidth / 2}px - 100%)`
},
bottom: {
x: `calc(${e.pageX}px - 50%)`,
y: `${e.pageY + popoverArrowWidth / 2}px`
}
}
setTimeout(() => {
addStyle(`
.my-popover {
inset: 0 auto auto 0 !important;
transform: translate(${popoverPlacementSettings[popover._popper.state.placement].x}, ${popoverPlacementSettings[popover._popper.state.placement].y}) !important;
}
`);
popover.tip.classList.add('my-popover');
}, 0)
}
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<svg id="mySVG" height="100" width="100">
<circle id="test" cx="50" cy="50" r="40" stroke="black" stroke width="3" fill="red" />
</svg>
关于javascript - 基于 SVG/鼠标位置定位 Bootstrap Popover,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68397653/