我正在使用D3的进入/退出选择,我也希望在鼠标悬停事件上添加转换.
问题是,如果我在移动时将鼠标悬停在字母上,它们会冻结,因为位置转换会中断.
这是一个JSFiddle演示问题:http://jsfiddle.net/uEuE4/1/这是我用来将鼠标悬停事件添加到更新并输入选择的代码:
text
.on('mouseover', function(d) {
d3.select(this).transition().duration(100).style('fill', 'yellow');
});
Run Code Online (Sandbox Code Playgroud)
一旦完成所有其他转换,我怎么才能添加mouseover事件处理程序,以阻止字母冻结?
任何使代码更干的提示也会非常受欢迎.
您可以分配一个要转换的名称,然后该转换将仅被具有相同名称的新转换中断。
text
.on('mouseover', function(d) {
d3.select(this).transition("fillColor").duration(100).style('fill', 'yellow');
});
Run Code Online (Sandbox Code Playgroud)
小智 5
我赞成并同意@Jason 的回答,这将尝试通过一些说明和一个简单的演示来完成前面的内容,该演示可用作多种转换行为的游乐场。
检查您的代码,您有各种动画正在进行,但只需要命名其中两个即可摆脱所有转换“碰撞”,
这两个事件侦听器:
text.on('mouseover', function(d) {
d3.select(this).transition("texTr").duration(100).style('fill', 'yellow');
});
enter_text.on('mouseover', function(d) {
d3.select(this).transition("enterTexTr").duration(100).style('fill', 'yellow');
});
Run Code Online (Sandbox Code Playgroud)
长话短说,如果没有名字,D3 认为你的代码中的所有转换都是相同的,因此它会停止正在进行的转换(一个例子可以是一个字母转换)并用一个新的替换它(例如由事件侦听器),因为转换名称相同。
但有时所需的行为是明确停止某些元素的过渡;这可以使用.interrupt("transitionName"):
.on("mouseover", function() {
d3.select(this).interrupt("fadeOut")
.attr("fill", "orange")
})
.on("mouseout", function(d) {
d3.select(this).transition("fadeOut")
.duration(5000)
.attr("fill", "rgb(0, 0, " + (d * 10) + ")");
})
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果没有中断命令,我们将无法触发fill orange 直到fadeOut结束(5 秒!)。
这是你可以玩的FIDDLE :)
我还遇到了鼠标悬停中断转换的问题,并提出了以下(诚然是黑客)解决方案:在转换之前,将 css 样式添加pointer-events: none到svg元素;然后在转换后将其删除。实际上,我发现将样式应用到包含svg.
例如:
<div class="chart-container">
<svg></svg>
</div>
Run Code Online (Sandbox Code Playgroud)
然后:
$('.chart-container').addClass('no-mouse');
d3.select("svg").on("mouseover", function(d) {...})
.on("mouseout", function(d) {...})
.transition()
.duration(animDuration)
.attr("...", ...);
setTimeout(function() {
$('.chart-container').removeClass('no-mouse');
}, animDuration+10);
Run Code Online (Sandbox Code Playgroud)
与css:
.no-mouse {
pointer-events: none;
}
Run Code Online (Sandbox Code Playgroud)
适用于 Firefox、Safari、Chrome 甚至 IE 8。但渴望听到更简洁的解决方案。