【问题标题】:Is there a way to apply css on chart.js V3.7.0 tooltip without it being custom or external?有没有办法在 chart.js V3.7.0 工具提示上应用 css 而无需自定义或外部?
【发布时间】:2022-01-04 10:36:42
【问题描述】:

我有这个工具提示:

我想给它一些余地,以便更多地使用top。示例:

是工具提示代码:

              tooltip: {
                caretPadding: 3,
                caretSize: 0,
                displayColors: false,
                backgroundColor: 'rgba(45,132,180,0.8)',
                bodyFontColor: 'rgb(255,255,255)',
                callbacks: {
                  title: () => {
                    return
                  },
                  label: (ttItem) => ( `${ttItem.parsed.y} ppm` ),
                  afterBody: (ttItems) => (ttItems[0].label)
                }
              },

问题

如何将 css 赋予工具提示以使其更接近顶部?

【问题讨论】:

    标签: javascript chart.js


    【解决方案1】:

    你不能使用 CSS,因为它不是 HTML 样式,因为它是在画布上绘制的。

    您可以做的是为 chart.js 的工具提示提供自定义定位器。
    在下面的示例中,您可以看到如何做到这一点。增加我在顶部声明的yOffset 变量会将工具提示移动到更上方,增加我在顶部声明的xOffset 变量会将工具提示更向右移动:

    const yOffset = 10;
    const xOffset = 00;
    
    Chart.Tooltip.positioners.custom = function(items) {
      const pos = Chart.Tooltip.positioners.average(items);
    
      // Happens when nothing is found
      if (pos === false) {
        return false;
      }
    
      const chart = this.chart;
    
      return {
        x: pos.x + xOffset,
        y: pos.y - yOffset,
        yAlign: 'bottom',
      };
    }
    
    const options = {
      type: 'line',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            borderWidth: 1
          },
          {
            label: '# of Points',
            data: [7, 11, 5, 8, 3, 7],
            borderWidth: 1
          }
        ]
      },
      options: {
        plugins: {
          tooltip: {
            caretPadding: 3,
            caretSize: 0,
            displayColors: false,
            backgroundColor: 'rgba(45,132,180,0.8)',
            bodyFontColor: 'rgb(255,255,255)',
            callbacks: {
              title: () => {
                return
              },
              label: (ttItem) => (`${ttItem.parsed.y} ppm`),
              afterBody: (ttItems) => (ttItems[0].label)
            },
            position: 'custom'
          }
        }
      }
    }
    
    const ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
    </body>

    【讨论】:

    • 非常感谢!它有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多