我的問題:我有一些與圓形元素系結的資料點。現在,每當用戶點擊一個圓時,我想將其顏色改為紅色。為此,我想使用一個更新函式,在用戶每次點擊一個圓時呼叫該函式。由于我不僅想改變被點擊的圓圈,還想根據被點擊的圓圈改變其他元素,我需要以某種方式記住被點擊的圓圈。我看到在d3.js v3中,通過簡單地將資料保存到事件監聽器中的一個變數(clickedCircle)并在以后呼叫它來實作。然而,這在d3.js v6 中似乎已經不起作用了。在v6 中,什么是最好的方法呢?
快速 d3.js v3 示例(基本想法改編自這個圖表):
var data = [
{x: 10, y: 20}。
{x: 30, y: 10}。
{x: 20, y: 55}。
];
svg = d3.select(#div1)
.append("svg"/span>)
.attr("width", 100)
.attr("height", 100)
;
var circles;
var clickedCircle;
function update() {
circles = svg.selectAll("circle"/span>)
.data(data)
.enter()
.append("circle")
.attr("cx", function(d) { return d。 position.x } )
.attr("cy", function(d) { return d。 position.y } )
.attr("r",10)
.on("click", function(e, d) { clickedCircle = d; update() ; } )
;
圓圈
.style("fill"/span>, function(d) {
if (d === clickedCircle) {
return "red"
} else {
return "black" "black" }
}
})
;
}
uj5u.com熱心網友回復:
這是一個使用D3 v7的例子。 如果你點擊一個圓圈,該圓圈會變成紅色,其資料會顯示在一個文本標簽中。
。<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">/span>
<script src="https://d3js. org/d3.v7.js"></script>
</head>
<body>
<div id="圖表"> </div>>
<script>
// margin convention set up
const margin = { top: 10, bottom: 10, left: 10, right: 10 };
const width = 110 - margin.left - margin.right;
const height = 110 - margin.top - margin.bottom;
const svg = d3.select('#chart')
.append('svg')
.attr('width', width margin.left margin.right)
.attr('height', height margin.top margin.bottom) 。
const g = svg.append('g')
.attr('transform', `translate(${margin. left},${margin.top})`)。)
// data
const data = [
{ x: 10, y: 20 },
{ x: 30, y: 10 },
{ x: 20, y: 55 },
];
//畫圓 //畫圓
const circles = g.selectAll('circle')
.data(data)
.join('circle')
.attr('cx', d => d.x)
.attr('cy', d => D.y)
.attr('r'/span>, 10)
.attr('fill', 'black')
.on('click', update)。
//text label('click', update)
const label = g.append('text')
.attr('y', height) 。
//當圓圈被點擊的時候更新。
function update(event, d) {
//將所有圓圈重置為黑色。
circles.attr('fill', 'black') 。
//給點擊的圓圈涂上紅色。
d3.select(this).attr('fill','red')。
//更新標簽。
label.text(`x: ${d.x}, y: ${d.y}`)。)
}
</script>>
</body>
</html>/span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/320655.html
標籤:
上一篇:有沒有可能在visualcodestudio中暫時關閉tslint?
下一篇:D3.js突出顯示相關節點/鏈接
