我在这里有一个stackBlitz-https://stackblitz.com/edit/ng-tootltip?file=src/app/bar-图表.ts
我有一个条形图,当你把鼠标悬停在条形图上时,它会显示工具提示。
工具提示位于条形图上方,但对于较小的屏幕尺寸,我希望将工具提示定位在窗口中间。
我可以捕捉屏幕小的时候,我也有工具提示的宽度,所以我认为我需要定位它的宽度的一半。我只是在样式属性中坚持了如何使用它。
if (window.innerWidth < 500) {
const toolTipWidth = d3.select('.chart-tooltip').style('width');
const halfToolTipWidth = Number(toolTipWidth)/2;
d3.select('.chart-tooltip')
.style("left", 50 + "%") <- I need to minus the half width here
.style("top", 0 + "px")
.html(html)
}else{
d3.select('.chart-tooltip')
.style("left", d3.event.pageX - 30 + "px")
.style("top", 0 + "px")
.html(html)
}
您要查找的是CSS3 calc函数。您可以使用它来写入类似calc(50% - 10px)
的值(运算符必须用空格包围(。
这一点,加上对halfToolTipWidth
计算的修复,给出了NaN,你就完成了:
编辑:toolTipWidth
也已修复。
let tooltip = d3.select('.chart-tooltip');
if (window.innerWidth < 500) {
const toolTipWidth = tooltip.node().getBoundingClientRect().width;
const halfToolTipWidth = 40;
tooltip
.style("position", "absolute")
.style("left", "calc(50% - " + halfToolTipWidth +"px)")
.style("top", 0 + "px")
.html(html)
} else {
tooltip
.style("left", d3.event.pageX - 30 + "px")
.style("top", 0 + "px")
.html(html)
}
更新了Stacklitz。