You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Amcharts 5柱状图元素悬停时更改鼠标光标?

给Amcharts 5柱状图添加点击指针效果

解决方案

在Amcharts 5中,只需给柱状图的模板元素设置cursor: "pointer"属性,就能让鼠标悬停在柱子上时显示指针样式,提示用户该元素可点击。

具体实现

在你已有的点击事件代码上方,添加一行设置鼠标指针的代码即可:

// 设置柱子鼠标悬停为指针样式
series.columns.template.set("cursor", "pointer");

// 捕获柱状图点击事件
series.columns.template.events.on("click", function(ev) {
var country = ev.target.dataItem.dataContext.country;
console.log(country);
  // 对country变量进行操作
});

你也可以在创建ColumnSeries时直接配置柱子模板的cursor属性:

var series = chart.series.push(am5xy.ColumnSeries.new(root, {
  name: "Series 1",
  xAxis: xAxis,
  yAxis: yAxis,
  valueYField: "value",
  sequencedInterpolation: true,
  categoryXField: "country",
  tooltip: am5.Tooltip.new(root, {
    labelText: "{valueY}"
  }),
  // 直接在series配置中设置柱子模板的cursor
  columns: {
    template: am5.Column.new(root, {
      cursor: "pointer"
    })
  }
}));

修改后的完整代码

am5.ready(function() {
var root = am5.Root.new("chartdiv");

root.setThemes([
  am5themes_Animated.new(root)
]);

var chart = root.container.children.push(am5xy.XYChart.new(root, {
  panX: true,
  panY: true,
  wheelX: "panX",
  wheelY: "zoomX",
  pinchZoomX: true
}));

var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {}));
cursor.lineY.set("visible", false);

var xRenderer = am5xy.AxisRendererX.new(root, { minGridDistance: 30 });

xRenderer.grid.template.setAll({
  location: 1
})

var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
  maxDeviation: 0.3,
  categoryField: "country",
  renderer: xRenderer,
  tooltip: am5.Tooltip.new(root, {})
}));

var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
  maxDeviation: 0.3,
  renderer: am5xy.AxisRendererY.new(root, {
    strokeOpacity: 0.1
  })
}));

var series = chart.series.push(am5xy.ColumnSeries.new(root, {
  name: "Series 1",
  xAxis: xAxis,
  yAxis: yAxis,
  valueYField: "value",
  sequencedInterpolation: true,
  categoryXField: "country",
  tooltip: am5.Tooltip.new(root, {
    labelText: "{valueY}"
  })
}));

// 设置鼠标指针样式
series.columns.template.set("cursor", "pointer");

series.columns.template.events.on("click", function(ev) {
var country = ev.target.dataItem.dataContext.country;
console.log(country);
  // 对country变量进行操作
});

// 设置数据
var data = [{
  country: "USA",
  value: 20
}, {
  country: "China",
  value: 30
}, {
  country: "Japan",
  value: 40
}];

xAxis.data.setAll(data);
series.data.setAll(data);

}); // end am5.ready()
#chartdiv {
  width: 100%;
  height: 200px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>

<div id="chartdiv"></div>

内容的提问来源于stack exchange,提问作者Sha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 19:35:45