【问题标题】:Highcharts reflow does not work on class selectorHighcharts 重排不适用于类选择器
【发布时间】:2014-09-24 13:08:56
【问题描述】:

有没有人尝试在类选择器而不是 id 选择器上运行 High charts reflow() 函数?

查看示例,其中我有 2 个带有 1 个按钮的图表来切换其包含的 div 大小。 我还有另外 2 个按钮,一个按 id 重排图表,另一个按类别重排图表。

请注意,使用类选择器的那个似乎不会重排两个图表,并且它只会重排使用该类的第一个元素。

http://jsfiddle.net/deN74/1/

HTML:

<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

<div style="width: 600px">
    <div id="container1" class="needreflow" style="width: 400px; height: 300px; margin: 1em; border: 1px solid gray"></div>
    <div id="container2" class="needreflow" style="width: 400px; height: 300px; margin: 1em; border: 1px solid gray"></div>
</div>
<button id="set-div-size" class="autocompare">Toggle container size</button>
<button id="reflow-chart-byid" class="autocompare">Reflow charts by id selector</button>
<button id="reflow-chart-byclass" class="autocompare">Reflow charts by class selector</button>

JS:

$(function () {
    $('#container1').highcharts({
        xAxis: {
            categories: ['Jan', 'Feb', 'Mar']
        },

        series: [{
            data: [29.9, 71.5, 106.4]
        }]

    });
    $('#container2').highcharts({
        xAxis: {
            categories: ['Jan', 'Feb', 'Mar']
        },

        series: [{
            data: [29.9, 71.5, 106.4]
        }]

    });

    var wide = false;
    $('#set-div-size').click(function () {
        $('#container1').width(wide ? 400 : 500);
        $('#container2').width(wide ? 400 : 500);
        wide = !wide;
    });
    $('#reflow-chart-byid').click(function () {
        $('#container1').highcharts().reflow();
        $('#container2').highcharts().reflow();
    });
        $('#reflow-chart-byclass').click(function () {
        $('.needreflow').highcharts().reflow();
    });
});

【问题讨论】:

    标签: jquery class highcharts jquery-selectors reflow


    【解决方案1】:

    这是一个很好的观察,我相信它归结为.highcharts() 函数是如何实现的。正如所观察到的,它不会影响具有类选择器的多个元素,因为它仅适用于单个元素。

    如果您查看 the source code(第 971-1005 行)的函数,您可以看到这是代码:

    /**
     * Register Highcharts as a plugin in the respective framework
     */
    $.fn.highcharts = function () {
        ...
    
        // When called without parameters or with the return argument, get a predefined chart
        if (options === UNDEFINED) {
            ret = charts[attr(this[0], 'data-highcharts-chart')];
        }
    
        ...
        return ret;
    }
    

    返回值永远是this[0],也就是说无论你选择多少个元素,它都会返回第一个,根本不处理多个元素。

    reflow 也只会执行一次,因为highcharts 函数不会返回reflow 函数可以操作的列表。如果是这样,我猜reflow 函数也不支持多个元素。

    一种解决方案可能是使用.each 来遍历您使用选择器找到的每个容器,就像这样 (JSFiddle):

    $('.needreflow').each(function() { $(this).highcharts().reflow(); });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多