AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79526901
Accepted
Alice
Alice
Asked: 2025-03-22 11:30:25 +0800 CST2025-03-22 11:30:25 +0800 CST 2025-03-22 11:30:25 +0800 CST

Como saber o alvo real do evento de clique em echarts?

  • 772

Gostaria de adicionar um recurso de anotações ao meu diagrama echarts. Ele será marcado como uma linha pontilhada verde com um marcador quadrado verde se houver alguma anotação. Quando o usuário clicar no marcador quadrado verde, um pop-up será aberto para mostrar a anotação real.

Quando executo o comando abaixo, ele é acionado sempre que clico em qualquer lugar na linha do marcador de anotação. Como posso saber se o usuário clica especificamente no marcador quadrado verde?

myChart.on('click', "series.line", function(params) {
  console.log('normal click series.markLine', params)
})

Aqui está a demonstração: https://codepen.io/lora999/pen/azbGPKY

insira a descrição da imagem aqui

echarts
  • 1 1 respostas
  • 23 Views

1 respostas

  • Voted
  1. Best Answer
    kikon
    2025-03-24T06:19:11+08:002025-03-24T06:19:11+08:00

    Se você explorar paramsem seu myChart.on('click', "series.line", function(params){... você pode encontrar maneiras de identificar que o retângulo foi clicado. O mais direto parece ser params.event.target.type === 'rect'(testado com renderer svg também):

    myChart.on('click', "series.line", function(params) {
        if(params.event.target.type === 'rect'){
            console.log('Rectangle clicked');
            // use params.data.name or params.data._id to further
            // identify the target, if multiple annotations are added
        }
    });
    

    Trecho executável:

    const myChart = echarts.init(document.getElementById("chart-container"), null, {
       renderer: "canvas",
       useDirtyRect: false,
    });
    
    const option = {
        "useUTC": false,
        "grid": {
            "containLabel": true,
            "left": 35,
            "right": 40,
            "top": 40,
            "bottom": 40
        },
        "xAxis": {
            "type": "time",
        },
        "yAxis": {
            "type": "value",
        },
        "tooltip": {
            appendTo: 'body',
            "borderColor": "transparent",
            "show": true,
            "trigger": "axis",
            enterable: true,
        },
        "legend": {
            "orient": "horizontal",
            "show": true,
            "type": "scroll",
            "bottom": 0,
        },
        "series": [
            {
                "name": "series1",
                "data": [
                    [
                        1041811200000,
                        30429.64
                    ],
    
                    [
                        1043625600000,
                        99323.95999999999
                    ],
    
                    [
                        1050883200000,
                        4219.2
                    ],
                ],
                "connectNulls": true,
                "type": "line",
                "smooth": false,
    
                "showSymbol": false,
    
            },
            {
                id: 'Annotation',
                name: 'annotation',
                type: "line",
                markLine: {
                    symbol: 'none',
                    label: {
                        show: true,
                        formatter: '{icon|}',
                        rich: {
                            icon: {
                                height: 20,
                                width: 20,
                                backgroundColor: 'green',
                                _id:'__test__'
                            },
                            _id:'__test__'
                        }
                    },
                    data: [
                        {
                            name: 'annotationLine',
                            xAxis: 1043625600000,
                            lineStyle: {
                                width: 2,
                                color:'green'
                            },
                            _id: 'annotationLine'
                        },
                    ]
                }
    
            },
        ],
    };
    
    
    myChart.on('click', "series.line", function(params) {
        if(params.event.target.type === 'rect'){
            console.log('Rectangle clicked');
            // use params.data.name or params.data._id to further
            // identify the target, if multiple annotations are added
        }
    });
    
    
    myChart.setOption(option);
    
    window.addEventListener('resize', myChart.resize);
    <div id="chart-container" style="height:400px; min-width: 800px"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.6.0/echarts.min.js"></script>

    Entretanto, a solução mais segura é separar o retângulo da linha, torná-los duas anotações diferentes, o retângulo implementado como markPoint:

    const myChart = echarts.init(document.getElementById("chart-container"), null, {
       renderer: "canvas",
       useDirtyRect: false,
    });
    
    const option = {
        "useUTC": false,
        "grid": {
            "containLabel": true,
            "left": 35,
            "right": 40,
            "top": 40,
            "bottom": 40
        },
        "xAxis": {
            "type": "time",
        },
        "yAxis": {
            "type": "value",
        },
        "tooltip": {
            appendTo: 'body',
            "borderColor": "transparent",
            "show": true,
            "trigger": "axis",
            enterable: true,
        },
        "legend": {
            "orient": "horizontal",
            "show": true,
            "type": "scroll",
            "bottom": 0,
        },
        "series": [
            {
                "name": "series1",
                "data": [
                    [
                        1041811200000,
                        30429.64
                    ],
    
                    [
                        1043625600000,
                        99323.95999999999
                    ],
    
                    [
                        1050883200000,
                        4219.2
                    ],
                ],
                "connectNulls": true,
                "type": "line",
                "smooth": false,
    
                "showSymbol": false,
    
            },
            {
                id: 'Annotation',
                name: 'annotation',
                type: "line",
                markLine: {
                    symbol: 'none',
                    silent: true, // doesn't respond to click
                    label: {
                        show: false
                    },
                    data: [
                        {
                            name: 'annotationLine',
                            xAxis: 1043625600000,
                            lineStyle: {
                                width: 2,
                                color:'green'
                            },
                            _id: 'annotationLine'
                        },
                    ]
                },
                markPoint: {
                    symbol: 'rect',
                    symbolSize: 20,
                    symbolOffset: [0, -10],
                    itemStyle: {
                        color: 'green'
                    },
                    label: {
                        show: false,
                    },
                    data: [
                        {
                            name: 'annotationPoint',
                            coord: [1043625600000, 100000],
                            _id: 'annotationPoint'
                        },
                    ]
                }
    
            },
        ],
    };
    
    
    myChart.on('click', "series.line", function(params) {
        // in this scenario, only the markPoint is responding to clicks; but if other items are
        // added, params.componentType and/or params.data.name (or _id) may be used to identify the target
        if(params.componentType === 'markPoint'){
            console.log('Rectangle clicked', params.data.name);
        }
    })
    
    
    myChart.setOption(option);
    
    window.addEventListener('resize', myChart.resize);
    <div id="chart-container" style="height:400px; min-width: 800px"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.6.0/echarts.min.js"></script>

    ou usando o rótulo do ícone, como no código original (renderizador svg usado):

    const myChart = echarts.init(document.getElementById("chart-container"), null, {
       renderer: "svg",
       useDirtyRect: false,
    });
    
    const option = {
        "useUTC": false,
        "grid": {
            "containLabel": true,
            "left": 35,
            "right": 40,
            "top": 40,
            "bottom": 40
        },
        "xAxis": {
            "type": "time",
        },
        "yAxis": {
            "type": "value",
        },
        "tooltip": {
            appendTo: 'body',
            "borderColor": "transparent",
            "show": true,
            "trigger": "axis",
            enterable: true,
        },
        "legend": {
            "orient": "horizontal",
            "show": true,
            "type": "scroll",
            "bottom": 0,
        },
        "series": [
            {
                "name": "series1",
                "data": [
                    [
                        1041811200000,
                        30429.64
                    ],
    
                    [
                        1043625600000,
                        99323.95999999999
                    ],
    
                    [
                        1050883200000,
                        4219.2
                    ],
                ],
                "connectNulls": true,
                "type": "line",
                "smooth": false,
    
                "showSymbol": false,
    
            },
            {
                id: 'Annotation',
                name: 'annotation',
                type: "line",
                markLine: {
                    symbol: 'none',
                    silent: true, // doesn't respond to click
                    label: {
                        show: false
                    },
                    data: [
                        {
                            name: 'annotationLine',
                            xAxis: 1043625600000,
                            lineStyle: {
                                width: 2,
                                color:'green'
                            },
                            _id: 'annotationLine'
                        },
                    ]
                },
                markPoint: {
                    symbol: 'rect',
                    symbolSize: 20,
                    symbolOffset: [0, -10],
                    itemStyle: {
                        color: 'green'
                    },
                    label: {
                        show: false,
                    },
                    data: [
                        {
                            name: 'annotationPoint',
                            coord: [1043625600000, 100000],
                            _id: 'annotationPoint'
                        },
                    ]
                }
    
            },
        ],
    };
    
    
    myChart.on('click', "series.line", function(params) {
        // in this scenario, only the markPoint is responding to clicks; but if other items are
        // added, params.componentType and/or params.data.name (or _id) may be used to identify the target
        if(params.componentType === 'markPoint'){
            console.log('Rectangle clicked', params.data.name);
        }
    });
    
    
    myChart.setOption(option);
    
    window.addEventListener('resize', myChart.resize);
    <div id="chart-container" style="height:400px; min-width: 800px"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.6.0/echarts.min.js"></script>

    • 1

relate perguntas

  • Definir borda no Apache eChart ao redor do gráfico

  • Quando atualizo os dados para mostrar em um gráfico de funil usando echarts, os rótulos saem da tela

  • Existe uma maneira de criar um gráfico de pizza cheio de pontos em ECharts?

  • Echarts como fazer o gráfico abranger 2 (ou mais) células da grade

  • Echarts markLine não aparece. (Gráfico de barras)

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve