Настраиваемая всплывающая подсказка в строке графика nvd3. js - PullRequest
0 голосов
/ 06 августа 2020

Как создать настраиваемую всплывающую подсказку в lineChart из nvd3. js?, Я хочу добавить «общее» значение во всплывающую подсказку примерно так

enter image description here

I've tried to call the chart.tooltip.contentGenerator, to create a custom tooltip, but the data is empty

chart.tooltip.contentGenerator(function(data) {
    console.log(data) //empty
});

i'am using nvd3 version 1.8.5 and d3 version 3.5.9 only, here's my fiddle: образец

Ответы [ 3 ]

0 голосов
/ 08 августа 2020

Спасибо, @Dave Miller!

Я добавил этот код, чтобы во всплывающую подсказку было включено «общее»

chart.interactiveLayer.tooltip.contentGenerator(function(data) {
        var dt     = data.value;    
        var series = '';
        var total  = 0;

        $.each(data.series, function(k,v){
            series += '<tr class="nv-pointer-events-none">'+
                            '<td class="legend-color-guide"><div style="background-color: '+v.color+'"></div></td>'+
                            '<td class="key">'+v.key+'</td>'+
                            '<td class="value">'+v.value.toFixed(2)+'</td>'+
                      '</tr>';
            total += v.value;
        });
      
        var head = '<thead>'+
                        '<tr>'+
                            '<th colspan="2"><strong class="x-value">'+dt+'</strong></th>'+
                            '<th>Total: '+total.toFixed(2)+'</th>';
                        '</tr>'+
                   '</thead>';
      
        return '<table class="nv-pointer-events-none">'+
                    head+
                    '<tbody>'+series+'</tbody>'+
                '</table>';
}); 

Проблема с этим, он не выделяет сфокусированный цвет во всплывающей подсказке, например,

enter image description here

Any answer to fix this completely? hehe

working fiddle with "chart.interactiveLayer.tooltip.contentGenerator" образец

0 голосов
/ 25 августа 2020

@ Дэйв Миллер

Спасибо, сэр, я тоже понял, извините, если я не поделился. я делаю это так \

введите описание изображения здесь

Может, я проделал длинный метод, в любом случае спасибо!

0 голосов
/ 07 августа 2020

Пожалуйста, попробуйте использовать chart.interactiveLayer.tooltip.contentGenerator. Тестируя ваш код с помощью этой строки, я смог просмотреть значения внутри переменной данных, как вы можете видеть ниже:

attached capture.

From here you could construct or edit your custom tooltip as you wish. Let me know if it works for you.

[EDIT - SUGGESTION TO INCLUDE EVENT BEHAVIOR]

Looking inside NVD3, I realized that the tooltip's contentGenerator contains all specific code to add events behavior for tooltip. If you take a look at the original tooltip, it uses a class called highlight to mark focused color, but the custom tooltip has not implemented this events and does not highlith focused color.

I know it's a step back, once you have made you own code for thisd custom tooltip, but seems that the only way to achieve this is to rebuild your code to inlcude event behavior. Maybe starting from the orginal code that NVD3 includes to create tooltip usign contetGenerator will help (thats the way I would take, but it's up to you if you prefer to implement this on your current code).

If you want to take a look at this code, please find tooltip.js for your NVD3 version or visit this Ссылка GitHub

В этом файле, если вы проверите в строке 83 просто поиск « выделить » в файле, вы увидите, как событие enter () реализуется для всех tr элементов внутри тела таблицы, добавляя имя класса подсветку .

var trowEnter = tbodyEnter.selectAll("tr")
    .data(function(p) { return p.series})
    .enter()
    .append("tr")
    .classed("highlight", function(p) { return p.highlight});

Я предлагаю взять весь этот код (я имею в виду все внутри contentGenerator) для вашего пользовательского contentGenerator, чтобы вы могли убедиться, что весь код HTML сгенерирован в соответствии с оригиналом, даже со связанным поведением, а затем переопределить его, чтобы включить настройку, которую вы сделали для заголовка.

Пожалуйста, попробуйте это и дайте мне знать, удастся ли вам решить проблему.

...