如何将 ToolTip 固定在页面右上方,距离右侧 15% 页面宽度?
在当前代码中,只有当图片的宽度或高度大于 150px 时,才会将 tooltip 定位到页面的右上方。要将 tooltip 固定在页面的右上方,右边距离页面右侧 15% 页面宽度的位置,可以按照以下步骤修改代码:
-
在图片宽度或高度大于 150px 的条件判断中,添加一个新的判断条件,判断当前 tooltip 是否需要固定在页面右上方。
-
如果需要固定在页面右上方,则设置 tooltip 的 position 属性为 fixed,同时设置 right 和 top 属性,将 tooltip 定位到页面的右上方。
-
如果不需要固定在页面右上方,则按照原始的逻辑计算 tooltip 的 left 和 top 值,将 tooltip 定位在鼠标位置的右下方。
修改后的代码示例:
if (img.width > 150 || img.height > 150) {
// 如果图片宽度或高度大于 150px,则判断是否需要固定在页面右上方
const wrapperRect = document.querySelector('.category-options-wrapper').getBoundingClientRect();
const tooltipWidth = tooltip.offsetWidth;
const right = wrapperRect.right - wrapperRect.width * 0.15;
const top = 10;
if (tooltipHeight > wrapperRect.height - 20) {
// 如果 tooltip 高度大于 wrapper 的高度 - 20,则设置 tooltip 的最大高度
tooltip.style.maxHeight = (wrapperRect.height - 20) + 'px';
}
tooltip.style.position = 'fixed';
tooltip.style.right = right + 'px';
tooltip.style.top = top + 'px';
} else {
// 如果图片宽度或高度小于等于 150px,则按照原始逻辑计算 tooltip 的 left 和 top 值
let left = mouseX - wrapperRect.left + 10;
let top = mouseY - wrapperRect.top + 10;
if (!imgSrc || !tooltip.querySelector('img')) {
left = e.pageX + 10;
top = e.pageY + 10;
} else if (left + tooltipWidth > wrapperRect.left + wrapperRect.width) {
// tooltip 超出右侧边界
left = wrapperRect.left + wrapperRect.width - tooltipWidth;
}
if (top + tooltipHeight > wrapperRect.top + wrapperRect.height) {
// tooltip 超出下方边界
top = wrapperRect.top + wrapperRect.height - tooltipHeight;
}
tooltip.style.left = left + 'px';
tooltip.style.top = top + 'px';
}
代码解释:
- 首先获取
.category-options-wrapper元素的 boundingClientRect,以获得其宽度和高度信息。 - 计算 tooltip 的 right 属性值:
right = wrapperRect.right - wrapperRect.width * 0.15,即距离页面右侧 15% 页面宽度的位置。 - 如果 tooltip 高度超过
.category-options-wrapper的高度,则设置 tooltip 的最大高度,防止其超出页面。 - 设置 tooltip 的 position 为 fixed,将 tooltip 固定在页面右上方。
- 如果图片宽度或高度小于等于 150px,则按照原始逻辑计算 tooltip 的 left 和 top 值,将 tooltip 定位在鼠标位置的右下方。
原文地址: https://www.cveoy.top/t/topic/ohBb 著作权归作者所有。请勿转载和采集!