gpt4 book ai didi

javascript - 单击将标签锚定到 Chart.js 中的相应部分 HTML

转载 作者:行者123 更新时间:2023-11-30 16:43:31 25 4
gpt4 key购买 nike

我有一个图表,当点击每个图表标签时,滚动会移动到它们各自的 HTML 部分。我正在使用 Chart.js,当我单击标签时,我唯一能做的就是发出警报。

Javascript

// Chart
var barData = {
labels: ['Red', 'Orange', 'Yellow', 'Green']
};


var pieData = [{
value: 40,
color: "#ad1f27",
highlight: "#ad474c",
label: "Red"
}, {
value: 40,
color: "#c26828",
highlight: "#c27e4d",
label: "Orange"
}, {
value: 10,
color: "#c3b830",
highlight: "#c3bc6b",
label: "Yellow"
}, {
value: 10,
color: "#14773c",
highlight: "#2da15b",
label: "Green"
}];

var options = {
segmentShowStroke: false
};

Chart.defaults.global.responsive = true;

var context = document.getElementById('chartDonnut').getContext('2d');
var skillsChart = new Chart(context).Doughnut(pieData, options);

$("#chartDonnut").click(function(evt) {
var activePoints = skillsChart.getSegmentsAtEvent(evt);
var url = activePoints[0].label + activePoints[0].value + activePoints[0].x + activePoints[0].y;
alert(url);
});

jsfiddle

最佳答案

要访问所选字段,只需使用内部链接即可。

您需要添加修改 html 如下:

<canvas id="chartDonnut"></canvas>
<div id="red" class="redSection">
<p>Red Section</p>
</div>
<div id="orange" class="orangeSection">
<p>Orange Section</p>
</div>
<div id="yellow" class="yellowSection">
<p>Yellow Section</p>
</div>
<div id="green" class="greenSection">
<p>Green Section</p>
</div>

对于 jquery 代码,它将是这样的:

// Chart
var barData = {
labels: ['Red', 'Orange', 'Yellow', 'Green']
};


var pieData = [{
value: 40,
color: "#ad1f27",
highlight: "#ad474c",
label: "Red"
}, {
value: 40,
color: "#c26828",
highlight: "#c27e4d",
label: "Orange"
}, {
value: 10,
color: "#c3b830",
highlight: "#c3bc6b",
label: "Yellow"
}, {
value: 10,
color: "#14773c",
highlight: "#2da15b",
label: "Green"
}];

var options = {
segmentShowStroke: false
};

Chart.defaults.global.responsive = true;

var context = document.getElementById('chartDonnut').getContext('2d');
var skillsChart = new Chart(context).Doughnut(pieData, options);

$("#chartDonnut").click(function(evt) {
var activePoints = skillsChart.getSegmentsAtEvent(evt);
var url = activePoints[0].label + activePoints[0].value + activePoints[0].x + activePoints[0].y;
if(activePoints[0].label=="Red"){
window.location="#red";
}
if(activePoints[0].label=="Orange"){
window.location="#orange";
}
if(activePoints[0].label=="Yellow"){
window.location="#yellow";
}
if(activePoints[0].label=="Green"){
window.location="#green";
}
});

关于javascript - 单击将标签锚定到 Chart.js 中的相应部分 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31573717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com