gpt4 book ai didi

javascript - 通过数据 ID 选择对象并设置对象样式

转载 作者:行者123 更新时间:2023-12-01 04:10:19 24 4
gpt4 key购买 nike

我正在尝试进行鼠标悬停事件,其中圆半径变大,并且相应的数据标签增加字体大小。数据标签位于图表本身的圆圈上。所以我的想法是有两个函数,一个通过过渡来设计圆圈的漂亮和平滑,并使用一个单独的函数和补间来设计文本的样式。 我想同时调用这两个函数,并让它们仅设置数据绑定(bind)与其“id”匹配的样式对象。Id 只是我从 .tsv 解析的索引。这个想法是文本和圆圈都有相同的“id”。

!boring circle svg code above
.on('mouseenter', function(d) {circle_event(this); text_event(this);})

function circle_event(id) {
if (d3.select(this).data==id) {
d3.select(this)
.transition()
.attr('r', radius*1.5)
.duration(500);
}
}

function text_event(id) {
if (d3.select(this).data==id) {
d3.select(this)
.transition()
.styleTween('font', function() {return d3.interpolate('12px Calibri', '20px Calibri' )
.duration(500);
}
}

出于某种原因,当我将鼠标悬停在圆圈上时,没有任何反应。开发工具没有任何错误。如果我不得不猜测,我误解了如何使用 d3 的 select 函数。

谢谢

编辑

请注意,我需要同时调用圆圈和文本样式函数,我将接受显示如何设置圆圈及其相应数据标签文本样式的答案只需将鼠标悬停在圆圈上。看来 this 不能同时用作圆形和文本对象。除了基于this之外的其他解决方案也是受欢迎的。

最佳答案

看来您编辑了您的问题,这极大地改变了事情。这是一种可行的方法,或者可以进行修改以使其发挥作用:

// Assumes circle & text objects have the same .x, .y and .id data bound to them and that 
// when created, they each have classes "circle-class" and "text-class" respectively

!boring circle svg code above
.on('mouseenter', function(d) {circle_event(d.x, d.y, d.id); text_event(d.x, d.y, d.id);})

function circle_event(x, y, id) {
d3.selectAll(".circle-class")
.filter(function (d) {
return (d.x === x) && (d.y == y) && (d.id == id);
})
.transition()
.attr('r', radius * 1.5)
.duration(500);
}

function text_event(x, y, id) {
d3.selectAll(".text-class")
.filter(function (d) {
return (d.x === x) && (d.y == y) && (d.id == id);
})
.transition()
.styleTween('font', function() {return d3.interpolate('12px Calibri', '20px Calibri' )
.duration(500);
}

或者,如果您构建圆形和文本 DOM 元素的创建,使它们具有兄弟关系,则可以使用 d3.select(this.previousElementSibling) 获取对文本选择的引用其中 this 是鼠标悬停在其上的圆形节点(参见此处 - How to access "previous sibling" of `this` when iterating over a selection? )。这种方法可以使用我上面回复中的代码。

关于javascript - 通过数据 ID 选择对象并设置对象样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41564194/

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