工具提示

工具提示:簡介

工具提示是滑鼠遊標懸停時出現的小方塊。(名片較寬,可以顯示在螢幕上的任何位置;工具提示一律附加在東西上,例如散佈圖上的點或長條圖上的長條)。

這份說明文件將說明如何在 Google 排行榜中建立及自訂工具提示。

指定工具提示類型

Google 圖表會自動為所有核心圖表建立工具提示。 根據預設,系統會將這些轉譯為 SVG,不過在 IE 8 之外,這些轉譯要求會顯示為 VML。您可以在核心圖表上建立 HTML 工具提示,方法是在傳送至 draw() 呼叫的圖表選項中指定 tooltip.isHtml: true。此外,您還可以建立工具提示動作

標準工具提示

沒有任何自訂內容時,系統會根據基本資料自動產生工具提示內容。將滑鼠遊標懸停在圖表中的任何長條上,即可查看工具提示。

將滑鼠遊標移到長條上,即可查看標準工具提示。

自訂工具提示內容

在本範例中,我們為 DataTable 新增資料欄,並加上工具提示角色來新增自訂內容至工具提示中。

注意泡泡圖視覺化內容支援這項功能。

        google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var dataTable = new google.visualization.DataTable();
        dataTable.addColumn('string', 'Year');
        dataTable.addColumn('number', 'Sales');
        // A column for custom tooltip content
        dataTable.addColumn({type: 'string', role: 'tooltip'});
        dataTable.addRows([
          ['2010', 600,'$600K in our first year!'],
          ['2011', 1500, 'Sunspot activity made this our best year ever!'],
          ['2012', 800, '$800K in 2012.'],
          ['2013', 1000, '$1M in sales last year.']
        ]);

        var options = { legend: 'none' };
        var chart = new google.visualization.ColumnChart(document.getElementById('tooltip_action'));
        chart.draw(dataTable, options);
      }

使用 HTML 工具提示

這個範例啟用 HTML 工具提示,並以此為基礎。請注意,在圖表選項中加入 tooltip.isHtml: true

google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var dataTable = new google.visualization.DataTable();
        dataTable.addColumn('string', 'Year');
        dataTable.addColumn('number', 'Sales');
        // A column for custom tooltip content
        dataTable.addColumn({type: 'string', role: 'tooltip'});
        dataTable.addRows([
          ['2010', 600,'$600K in our first year!'],
          ['2011', 1500, 'Sunspot activity made this our best year ever!'],
          ['2012', 800, '$800K in 2012.'],
          ['2013', 1000, '$1M in sales last year.']
        ]);

        var options = {
          tooltip: {isHtml: true},
          legend: 'none'
        };
        var chart = new google.visualization.ColumnChart(document.getElementById('col_chart_html_tooltip'));
        chart.draw(dataTable, options);
      }

這看起來不太一樣,但我們現在可以自訂 HTML。

自訂 HTML 內容

上述範例包含所有使用純文字內容的工具提示,但當您實際使用 HTML 標記進行自訂時,可以運用 HTML 工具提示的實際效果。若要啟用這項功能,您必須執行下列兩項操作:

  1. 在圖表選項中指定 tooltip.isHtml: true。這會指示圖表在 HTML 中繪製工具提示 (而非 SVG)。
  2. 使用 html 自訂屬性在資料表中標記整個資料欄或特定儲存格。包含工具提示角色和 HTML 屬性的資料表表格會是:
    dataTable.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}})

    注意:這項功能支援泡泡圖。對話框圖表的 HTML 工具提示內容無法自訂。

重要事項:請確認工具提示中的 HTML 來自可信任的來源。 如果自訂 HTML 內容包含任何使用者自製內容,則將內容逸出。否則您的美麗視覺呈現結果可能會開放 XSS 攻擊。

自訂 HTML 內容非常簡單,例如新增 <img> 標記或套用部分文字:

自訂 HTML 內容也可能包含動態產生的內容。我們在此新增工具提示,其中包含各個類別值的動態產生的資料表。由於工具提示已附加到資料列值,將滑鼠懸停在任一長條上,就會顯示 HTML 工具提示。

這個範例說明如何將自訂 HTML 工具提示附加到網域欄中。(在先前的範例中,它已附加至資料欄)。如要開啟網域軸的工具提示,請設定 focusTarget: 'category' 選項。

function drawChart() {
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('string', 'Country');
  // Use custom HTML content for the domain tooltip.
  dataTable.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});
  dataTable.addColumn('number', 'Gold');
  dataTable.addColumn('number', 'Silver');
  dataTable.addColumn('number', 'Bronze');

  dataTable.addRows([
    ['USA', createCustomHTMLContent('https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg', 46, 29, 29), 46, 29, 29],
    ['China', createCustomHTMLContent('https://upload.wikimedia.org/wikipedia/commons/f/fa/Flag_of_the_People%27s_Republic_of_China.svg', 38, 27, 23), 38, 27, 23],
    ['UK', createCustomHTMLContent('https://upload.wikimedia.org/wikipedia/commons/a/ae/Flag_of_the_United_Kingdom.svg', 29, 17, 19), 29, 17, 19]
  ]);

  var options = {
    title: 'London Olympics Medals',
    colors: ['#FFD700', '#C0C0C0', '#8C7853'],
    // This line makes the entire category's tooltip active.
    focusTarget: 'category',
    // Use an HTML tooltip.
    tooltip: { isHtml: true }
  };

  // Create and draw the visualization.
  new google.visualization.ColumnChart(document.getElementById('custom_html_content_div')).draw(dataTable, options);
}

function createCustomHTMLContent(flagURL, totalGold, totalSilver, totalBronze) {
  return '<div style="padding:5px 5px 5px 5px;">' +
      '<img src="' + flagURL + '" style="width:75px;height:50px"><br/>' +
      '<table class="medals_layout">' + '<tr>' +
      '<td><img src="https://upload.wikimedia.org/wikipedia/commons/1/15/Gold_medal.svg" style="width:25px;height:25px"/></td>' +
      '<td><b>' + totalGold + '</b></td>' + '</tr>' + '<tr>' +
      '<td><img src="https://upload.wikimedia.org/wikipedia/commons/0/03/Silver_medal.svg" style="width:25px;height:25px"/></td>' +
      '<td><b>' + totalSilver + '</b></td>' + '</tr>' + '<tr>' +
      '<td><img src="https://upload.wikimedia.org/wikipedia/commons/5/52/Bronze_medal.svg" style="width:25px;height:25px"/></td>' +
      '<td><b>' + totalBronze + '</b></td>' + '</tr>' + '</table>' + '</div>';
}

輪播工具提示

Google 圖表中的工具提示可透過 CSS 輪替。在下圖中,使用圖表的 CSS 將工具提示的順位旋轉 30°,緊接在圖表 div 之前:

<style>div.google-visualization-tooltip { transform: rotate(30deg); }</style>

請注意,這項功能僅適用於 HTML 工具提示 (也就是選項為 isHtml: true 的工具提示)。

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Year', 'Fixations'],
          ['2015',  80],
          ['2016',  90],
          ['2017',  100],
          ['2018',  90],
          ['2019',  80],
        ]);

        var options = {
          tooltip: { isHtml: true },    // CSS styling affects only HTML tooltips.
          legend: { position: 'none' },
          bar: { groupWidth: '90%' },
          colors: ['#A61D4C']
        };

        var chart = new google.visualization.ColumnChart(document.getElementById('tooltip_rotated'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <!-- The next line rotates HTML tooltips by 30 degrees clockwise. -->
    <style>div.google-visualization-tooltip { transform: rotate(30deg); }</style>
    <div id="tooltip_rotated" style="width: 400px; height: 400px;"></div>
  </body>
</html>

工具提示中的圖表

HTML 工具提示可以包含大部分您想要的 HTML 內容,即使是 Google 圖表也不例外。透過工具提示,使用者將遊標懸停在資料元素上時,即可取得額外資訊:這是使用者能夠快速掌握整體資訊的絕佳方法,同時讓使用者在需要時能深入研究相關細節。

下方的柱狀圖顯示最近幾個大型體育賽事的最新觀眾人數,並針對每個事件的工具提示顯示過去十年平均觀眾人數的折線圖。

這裡有幾點要注意首先,您需要繪製一個可列印圖表,用來顯示工具提示中的每一組資料集。其次,每個工具提示圖表都需要一個 "ready" 事件處理常式,我們將透過 addListener 來呼叫此程式來建立可列印的圖表。

重要事項:「所有」工具提示圖表都必須繪製在主要圖表之前。 這是擷取到要加進主要圖表「資料表」資料表的圖片。

重要部分
      // Draws your charts to pull the PNGs for your tooltips.
      function drawTooltipCharts() {

        var data = new google.visualization.arrayToDataTable(tooltipData);
        var view = new google.visualization.DataView(data);

        // For each row of primary data, draw a chart of its tooltip data.
        for (var i = 0; i < primaryData.length; i++) {

          // Set the view for each event's data
          view.setColumns([0, i + 1]);

          var hiddenDiv = document.getElementById('hidden_div');
          var tooltipChart = new google.visualization.LineChart(hiddenDiv);

          google.visualization.events.addListener(tooltipChart, 'ready', function() {

            // Get the PNG of the chart and set is as the src of an img tag.
            var tooltipImg = '<img src="' + tooltipChart.getImageURI() + '">';

            // Add the new tooltip image to your data rows.
            primaryData[i][2] = tooltipImg;

          });
          tooltipChart.draw(view, tooltipOptions);
        }
        drawPrimaryChart();
      }

      function drawPrimaryChart() {

        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Event');
        data.addColumn('number', 'Highest Recent Viewership');

        // Add a new column for your tooltips.
        data.addColumn({
          type: 'string',
          label: 'Tooltip Chart',
          role: 'tooltip',
          'p': {'html': true}
        });

        // Add your data (with the newly added tooltipImg).
        data.addRows(primaryData);

        var visibleDiv = document.getElementById('visible_div');
        var primaryChart = new google.visualization.ColumnChart(visibleDiv);
        primaryChart.draw(data, primaryOptions);

      }
完整網頁
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawTooltipCharts);

      // Set up data for visible chart.
      var primaryData = [
        ['NBA Finals', 22.4],
        ['NFL Super Bowl', 111.3],
        ['MLB World Series', 19.2],
        ['UEFA Champions League Final', 1.9],
        ['NHL Stanley Cup Finals', 6.4],
        ['Wimbledon Men\'s Championship', 2.4]
      ];

      // Set up data for your tooltips.
      var tooltipData = [
        ['Year', 'NBA Finals', 'NFL Super Bowl', 'MLB World Series',
        'UEFA Champions League Final', 'NHL Stanley Cup Finals',
        'Wimbledon Men\'s Championship'],
        ['2005', 12.5, 98.7, 25.3, 0.6, 3.3, 2.8],
        ['2006', 13.0, 90.7, 17.1, 0.8, 2.8, 3.4],
        ['2007', 9.3, 93.0, 15.8, 0.9, 1.8, 3.8],
        ['2008', 14.9, 97.5, 17.1, 1.3, 4.4, 5.1],
        ['2009', 14.3, 98.7, 13.6, 2.1, 4.9, 5.7],
        ['2010', 18.2, 106.5, 19.4, 2.2, 5.2, 2.3],
        ['2011', 17.4, 111.0, 14.3, 4.2, 4.6, 2.7],
        ['2012', 16.8, 111.3, 16.6, 2.0, 2.9, 3.9],
        ['2013', 16.6, 108.7, 12.7, 1.4, 5.8, 2.5],
        ['2014', 15.7, 111.3, 15.0, 1.9, 4.7, 2.4]
      ];

      var primaryOptions = {
        title: 'Highest U.S. Viewership for Most Recent Event (in millions)',
        legend: 'none',
        tooltip: {isHtml: true} // This MUST be set to true for your chart to show.
      };

      var tooltipOptions = {
        title: 'U.S. Viewership Over The Last 10 Years (in millions)',
        legend: 'none'
      };

      // Draws your charts to pull the PNGs for your tooltips.
      function drawTooltipCharts() {

        var data = new google.visualization.arrayToDataTable(tooltipData);
        var view = new google.visualization.DataView(data);

        // For each row of primary data, draw a chart of its tooltip data.
        for (var i = 0; i < primaryData.length; i++) {

          // Set the view for each event's data
          view.setColumns([0, i + 1]);

          var hiddenDiv = document.getElementById('hidden_div');
          var tooltipChart = new google.visualization.LineChart(hiddenDiv);

          google.visualization.events.addListener(tooltipChart, 'ready', function() {

            // Get the PNG of the chart and set is as the src of an img tag.
            var tooltipImg = '<img src="' + tooltipChart.getImageURI() + '">';

            // Add the new tooltip image to your data rows.
            primaryData[i][2] = tooltipImg;

          });
          tooltipChart.draw(view, tooltipOptions);
        }
        drawPrimaryChart();
      }

      function drawPrimaryChart() {

        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Event');
        data.addColumn('number', 'Highest Recent Viewership');

        // Add a new column for your tooltips.
        data.addColumn({
          type: 'string',
          label: 'Tooltip Chart',
          role: 'tooltip',
          'p': {'html': true}
        });

        // Add your data (with the newly added tooltipImg).
        data.addRows(primaryData);

        var visibleDiv = document.getElementById('visible_div');
        var primaryChart = new google.visualization.ColumnChart(visibleDiv);
        primaryChart.draw(data, primaryOptions);

      }
    </script>
  </head>
<body>
<div id="hidden_div" style="display:none"></div>
<div id="visible_div" style="height:300px"></div>
</body>
</html>

工具提示動作

工具提示也可以包含 JavaScript 定義的動作。以下提供一個簡單的工具提示,此按鈕包含當使用者按一下「See 本書範例」時,彈出對話方塊的動作。

當使用者選取派盤之心時,tooltip 選項就會觸發,進而執行 setAction 中定義的程式碼:

        google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Genre', 'Percentage of my books'],
          ['Science Fiction', 217],
          ['General Science', 203],
          ['Computer Science', 175],
          ['History', 155],
          ['Economics/Political Science', 98],
          ['General Fiction', 72],
          ['Fantasy', 51],
          ['Law', 29]
        ]);

        var chart = new google.visualization.PieChart(
          document.getElementById('tooltip_action'));

        var options = { tooltip: { trigger: 'selection' }};

        chart.setAction({
          id: 'sample',
          text: 'See sample book',
          action: function() {
            selection = chart.getSelection();
            switch (selection[0].row) {
              case 0: alert('Ender\'s Game'); break;
              case 1: alert('Feynman Lectures on Physics'); break;
              case 2: alert('Numerical Recipes in JavaScript'); break;
              case 3: alert('Truman'); break;
              case 4: alert('Freakonomics'); break;
              case 5: alert('The Mezzanine'); break;
              case 6: alert('The Color of Magic'); break;
              case 7: alert('The Law of Superheroes'); break;
            }
          }
        });

        chart.draw(data, options);
      }

動作可以是 visibleenabled 或兩者皆是。系統顯示 Google 圖表時,只會在可見時顯示工具提示動作,而只會在啟用時顯示可點擊動作。(已停用,但可見動作會顯示為灰色)。

visibleenabled 應為會傳回 true 或 false 值的函式。這些函式可以依附元素 ID 和使用者選項,讓您微調動作的瀏覽權限和可點擊性。

工具提示可以在 focus 以及 selection 上觸發。然而,使用工具提示動作時,建議採用 selection。這會導致工具提示持續存在,讓使用者能更輕鬆地選取動作。

當然,這些動作不必是快訊:您可以透過 JavaScript 執行的任何動作。我們在此新增兩項操作:一個用於放大圓餅圖的楔形調整架,另一個則縮小。

        google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Genre', 'Percentage of my books'],
          ['Science Fiction', 217],
          ['General Science', 203],
          ['Computer Science', 175],
          ['History', 155],
          ['Economics & Political Science', 98],
          ['General Fiction', 72],
          ['Fantasy', 51],
          ['Law', 29]
        ]);

        var chart = new google.visualization.PieChart(
          document.getElementById('tooltip_action_2'));

        var options = { tooltip: { trigger: 'selection' }};

        chart.setAction({
          id: 'increase',
          text: 'Read 20 more books',
          action: function() {
            data.setCell(chart.getSelection()[0].row, 1,
                         data.getValue(chart.getSelection()[0].row, 1) + 20);
            chart.draw(data, options);
          }
        });

        chart.setAction({
          id: 'decrease',
          text: 'Read 20 fewer books',
          action: function() {
            data.setCell(chart.getSelection()[0].row, 1,
                         data.getValue(chart.getSelection()[0].row, 1) - 20);
            chart.draw(data, options);
          }
        });

        chart.draw(data, options);
      }

為資料加上註解

您可以使用 annotationText 而不是 tooltip 資料欄做為角色,直接將文字重疊於 Google 圖表上。(將滑鼠遊標懸停在註解上可看見工具提示)。

function drawChart() {
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('string', 'Year');
  dataTable.addColumn('number', 'USA');
  dataTable.addColumn({type: 'string', role: 'annotation'});
  dataTable.addColumn({type: 'string', role: 'annotationText', p: {html:true}});
  dataTable.addColumn('number', 'China');
  dataTable.addColumn('number', 'UK');
  dataTable.addRows([
    ['2000',  94, '',  '', 58, 28],
    ['2004', 101, '',  '', 63, 30],
    ['2008', 110, 'An all time high!', '<img width=100px src="https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg">', 100, 47],
    ['2012', 104, '',  '', 88, 65]
  ]);

  var options = { tooltip: {isHtml: true}};
  var chart = new google.visualization.LineChart(document.getElementById('tt_6_annotation'));
  chart.draw(dataTable, options);
}

支援的圖表

目前下列圖表類型支援 HTML 工具提示:

如果您使用的是 annotationTexttooltip 角色,請參閱角色說明文件,瞭解日後的異動,以及如何避免日後的問題發生。