【问题标题】:Is there a way to have a toggled legend item save its state on refresh?有没有办法让切换的图例项在刷新时保存其状态?
【发布时间】:2018-07-12 19:53:10
【问题描述】:

目前有没有办法让图例项在刷新时保存其状态?例如,我有一个包含 3 条线的图:a、b 和 c。我关闭 c 线,因此它不会显示在图表上。目前刷新页面时,a、b、c 会再次显示在图表上。有没有办法让它记得关闭c?

【问题讨论】:

  • 要在刷新过程中存储信息,您可能需要使用 cookie 或数据库后端。

标签: highcharts


【解决方案1】:

使用localStorage 功能存储图表系列可见性的当前状态。您需要在单击图例项时更改本地存储位置的状态,因此只需使用plotOptions.series.events.legendItemClick 处理程序,然后在每个图表load 事件上,根据存储的信息设置您的系列可见性。

  chart: {
    events: {
      load: function() {
        var series = this.series;
        // If there is no legend items visibility flags saved in local storage, save them.
        if (!localStorage.legendItems) {
          let legend = []
          series.forEach(function(series) {
            legend.push(series.visible)
          })
          localStorage.legendItems = legend.toString()
         //
        } else {
          let legend = localStorage.legendItems.split(',')
          let legendBooleans = []
          legend.forEach(function(elem) {
            var isTrueSet = (elem === 'true')
            legendBooleans.push(isTrueSet)
          })
          legendBooleans.forEach(function(state, i) {
            series[i].update({
                visible: state
            })
          })
        }
      }
    }
  },
  plotOptions: {
    series: {
      events: {
        legendItemClick: function() {
          var series = this.chart.series
          var index = this.index
          var legend = localStorage.legendItems.split(',')
          var legendBooleans = []
          legend.forEach(function(elem) {
            var isTrueSet = (elem === 'true')
            legendBooleans.push(isTrueSet)
          })
          // toggle series visibility flag and override it in local storage
          legendBooleans[index] = !legendBooleans[index]
          localStorage.legendItems = legendBooleans.toString()
        }
      }
    }
  },

如果你有任何问题,尽管问。

现场示例:https://jsfiddle.net/os961gke/

API 参考:https://api.highcharts.com/highcharts/plotOptions.series.events.legendItemClick https://api.highcharts.com/highcharts/chart.events.load

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多