Highcharts中如何外部修改pointStart

时间:2024-11-07 15:34:44
相信很多童鞋都在用Highcharts做图表,使用时当然就会产生各种各样的需求,今天遇到一个问题,搞了一上午才搞定:在服务端拼装好options的json串传到前段,但是有个问题,JSONObject方法是防止代码注入的,所以纯js代码都会被加上“”,这样就无法直接执行了。
同时,我所用的highchart时间轴使用pointStart:Date.UTC(2012,10,10),这样的js代码设置的,这就需要我在前段利用js设置pointStart值,试了好久,源码看了也木有用。。。最后还是用firebug调试,看了下options变量的组成结构才搞定:
options.plotOptions.series.pointStart = Date.UTC( now.getFullYear(), now.getMonth(), now.getDay() );
使用上面的语法设置就可以啦,以下是我的全部代码示例(可拷贝出去直接运行):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    var chart;
    $(document).ready(function() {
     var now = new Date()
     var options = {
         "plotOptions":{
         "series":{
         //"pointStart":Date.UTC( 2000, 1, 2 ),
         "pointInterval":3600*1000*24},
         "line":{"enableMouseTracking":true,"dataLabels":{"enabled":true}}},"title":{"text":"关键词趋势分析"},"yAxis":{"title":{"text":"数量"}},"subtitle":{"text":""},"chart":{"renderTo":"container","type":"line"},"xAxis":{"labels":{"formatter":function(){ return Highcharts.dateFormat("%m-%d", this.value); }},"type":"datetime"},"tooltip":{"xDateFormat":"%Y-%m-%d %A","shared":true,"enabled":true,"crosshairs":true},
            series: [{
                name: 'Tokyo',
                data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
            }, {
                name: 'New York',
                data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
            }, {
                name: 'Berlin',
                data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
            }, {
                name: 'London',
                data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
            }]
        };
        //alert(now.getFullYear());
        //options.pointInterval = 3600*1000*24;
        //alert(options.plotOptions.pointStart);
       options.plotOptions.series.pointStart = Date.UTC( now.getFullYear(), now.getMonth(), now.getDay() );//就是这一部啦~
        //alert(options.plotOptions.series.pointStart);
        Highcharts.setOptions(options);
       chart = new Highcharts.Chart(options);
    });
});
</script>
</head>
<body>
<script src="../../js/highcharts.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>