echarts的tooltip中动态渲染自定义内容

有这样一个需求:需要在图表最后那个hover或者click数据点时,能够在浮层(tooltip)中展示详细数据,并且这个浮层有规定样式,点击某个数据需要对应页面。也就是说浮层中的内容/样式/事件都需要自定义。

简单实例是这样的:数据动态渲染且绑定事件

对照echarts的api发现没有提供自定义的口,在github的issues找到了回答,不支持!!formatter返回html也不支持!!

晚上找到了简单的代码,试了下,传html可以渲染,代码在最后!把它放到项目中多少经历了些坎坷。。。

  设置series:

1.图中灰点是renderItempoint确定的,数据1的x轴为[2012-01-01,2012-01-02,2012-01-03,2012-01-04],当灰点的数据是一维非连续的情况:[2012-01-02,2012-01-04],如果希望数据点对应到x轴,需要将xAxis: {type: 'time'},而category会从x轴0点开始渲染。

2.formatter返回根据数据动态拼接的字符串模板

        // 生成series
        createSeries() {
            // 数据点的样式和位置
            function renderItempoint(param, api) {
                let point = api.coord([api.value(0), 0]);
                return {
                    type: 'group',
                    children: [{
                        type: 'circle',
                        shape: {cx: point[0], cy: 20, r: 8},
                        style: {fill: '#bfbfbf'}
                    }]
                };
            }
            return {
                type: 'custom',
                renderItem: renderItempoint,
                data: [],// 你的x轴数据,可以是不连续的
                tooltip: {
                    trigger: 'item',
                    triggerOn: 'click',
                    formatter: (obj) => {
                        // 创建tooltip formatter渲染自定义组件内容
                        this.createTooltipComponent(obj);
                        // tooltip formatter渲染自定义组件容器
                        let tooltipContent = '';
                        // 遍历data
                        this.Data.find(val => val.date === obj.data).list.map(item => {
                            tooltipContent += `
                                <div>
                                    <div style="width:120px;display:inline-block">${this.dataMap(item.type)}: </div>
                                    <a style="color:#6ea0ff" id="tooltipNumber${item.type}">${item.number}</a>
                                </div>`;
                        });
                        return `<div id="tooltipContainer" style="width:180px;padding:10px">${tooltipContent}</div>`;
                    }
                }
            };
        },

  绑定事件:定时器中延时才可获取dom节点,随后通过addEventListener绑定事件,事件名是动态拼接的。注意传参的方式!

        // 生成Tooltip内部html
        createTooltipComponent(obj) {
            setTimeout(() => {
                function handle(type, date) {
                    // 时间:xxxx-xx-xx转为精确到天的时间戳
                    let Timestamp = Date.parse(new Date(date));
                    // 跳转列表
                    window.open(`/xxx/list?type=${type}&date=${Timestamp}`, '_blank');
                }
                this.Data.find(val => val.date === obj.data).list.map(item => {
                    var tooltipNumber = document.getElementById(`tooltipNumber${item.type}`);
                    tooltipNumber.addEventListener('click', function (type, data) { 
                        handle(item.type, obj.data);
                    }, false);
                });
            }, 200);
        },

追加网上比较简单的例子:可以先试试再动手

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>tooltip</title>
    <style>
        #specialLook{
            background-color: #73CD11;
            width: 60px !important;
            height: 20px !important;
            border-radius: 2px;
            padding: 2px 8px;
            font-size: 12px !important;
            cursor: pointer;
            pointer-events: all;
            border: 0px;
            color: #fff;
        }
    </style>
</head>
<body>
    <div 
        style="width: 100%;height:450px"
        id="chartsUse"
    >
    </div>
    <script src="./echarts.common.min.js"></script>
    <script>
        function eventInfo(obj, color, val, date) { 
            console.log(date)
            console.log(val)
            var chartsInfo = echarts.init(obj);
            chartsInfo.on('click', function (params) {
                console.log('点击转折点 - ',params)
            });
            chartsInfo.setOption({
                color:['#F3052F','#2D3CED','#e4393c','#F5C300','#2F4F4F'],
                legend: {
                    x: 'center',
                    y: 'bottom',
                    itemGap: 80,
                    data:['事件统计','人数统计']
                },
                calculable : true,
                xAxis : [
                    {
                        type : 'category',
                        boundaryGap : false,
                        data : [
                            '10:00','10:30','11:00','11:30',
                            '12:00','12:30','13:00','13:30',
                            '14:00','14:30','15:00','15:30',
                            '16:00','16:30','17:00','17:30',
                            '18:00'
                        ]
                    }
                ],
                tooltip: {
                    axisPointer: {
                        type: 'cross'
                    },
                    triggerOn: 'click',
                    alwaysShowContent:true,
                    trigger:'axis',
                    formatter:function(params){
                        var html = '';
                        if(params.length>0){
                            Xindex = params[0].dataIndex;
                            html+= '<br>';
                            for ( var int = 0; int < params.length; int++) {
                                if(int == 0){
                                    html+='&nbsp;&nbsp;&nbsp;<button class="fr btn closeHandle" id="specialLook"  onclick="lookVideoGo()">查 看</button><br>';   
                                }else{
                                    html+='<br>';
                                }
                            }
                        }
                        return html;
                    },
                },
                yAxis : [
                    {
                        type : 'value',
                        interval:10,
                    }
                ],
                series : [
                    {
                        type: 'custom',
                        renderItem: function () {
                            // ...
                            return {
                                type: 'group',
                                children: [{
                                    type: 'circle'
                                    // ...
                                }, {
                                    type: 'circle',
                                    name: 'aaa',
                                    // 用户指定的信息,可以在 event handler 访问到。
                                    info: 12345,
                                    // ...
                                }]
                            };
                        },
                        name:'一维数据',
                        type:'line',
                        data:val.action,
                        z: 11
                        
                    },
                    {
                        name:'事件统计',
                        type:'line',
                        data:val.eventVal,
                    },
                    {
                        name:'人数统计',
                        type:'line',
                        data:val.peopleVal
                    },
                ]
            })
            return chartsInfo;
        }
        function echartsStrat(){
            chartsUseChart1 = '';
            eventCData = {
                'action': [100,'-',100,100,100,100,100,100,100,100,100,100,100,100,100,100,23],
                'eventVal': [3,5,25,53,73,25,32,55,32,21,32,12,33,12,34,65,23],
                'peopleVal': [5,23,35,12,40,37,11,31,20,40,40,35,78,100,37,23,2,4,1]
            }
            var echartsDate = '2019-08-23' // 日期 自定
            chartsUseChart1 = eventInfo(document.getElementById('chartsUse'), '#50E3C2', eventCData , echartsDate);
        }
        echartsStrat();
        // 查看该时间段
        function lookVideoGo(){
            console.log('时间')
        }
    </script>
</body>
</html>

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值