【问题标题】:D3 position tooltip at smaller screen sizesD3 在较小的屏幕尺寸上定位工具提示
【发布时间】:2018-11-19 17:56:49
【问题描述】:

我在这里有一个 stackBlitz - https://stackblitz.com/edit/ng-tootltip?file=src/app/bar-chart.ts

当您将鼠标悬停在条形上时,我有一个带有工具提示的条形图。

工具提示位于条形上方,但在小屏幕尺寸下,我想将工具提示放置在窗口中间。

我可以在屏幕很小的时候进行捕捉,而且我也有工具提示的宽度,所以我认为我需要定位它的宽度的一半。我只是坚持如何在 style 属性中使用它。

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)
}

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    您正在寻找的是 CSS3 calc function。 你可以用它来写像calc(50% - 10px)这样的值(操作符必须被空格包围)。

    这个,加上对给出 NaN 的 halfToolTipWidth 计算的修复,你就完成了:

    编辑: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)
    }
    

    Updated Stackblitz.

    【讨论】:

    • Zim,更新后的 Stackblitz 似乎不起作用,工具提示需要位于图表的中心
    • 你的意思是垂直的?
    • 我更新了 toolTipWidth 计算错误,导致您认为工具提示未正确居中(水平)。如果您还需要垂直居中,您可以按照完全相同的步骤操作。
    • 另外,作为一般建议,您应该避免一次又一次地进行相同的选择并尽可能多地存储它!
    • 我如何在这里存储选择?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2014-03-22
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多