d3.js中的转换挂起



我在d3.js(fiddle(中的一个简单动画遇到了问题

我的目标是当鼠标悬停在红色方块上时,让圆圈向下移动50个像素。

当我的光标悬停在红色方块右上角/左上角的圆圈上方时,圆圈会平滑过渡。但是,当我的光标悬停在圆圈内部或红色正方形左下/右下部分的圆圈下方时,圆圈要么停止在我的光标处移动,要么根本不移动。

我想这与我的动画功能有关

function mouseOverLogo() {
cir.transition()
.duration(2000)
.attr('transform', 'translate(0, 50)');
}
function mouseOutLogo() {
cir.transition()
.duration(2000)
.attr('transform', 'translate(0, -50');
}

一般来说,我是d3.js和js的新手。如有任何帮助,我们将不胜感激。

这里有一个片段:

const svg = d3.select('svg');
const width = svg.attr('width');
const height = svg.attr('height');
const g = svg
.append('g')
.attr('transform', `translate(${width / 2}, ${height / 2})`);
var cir_backboard = g
.append('rect')
.attr('x', 50)
.attr('y', 50)
.attr('width', 60)
.attr('height', 60)
.attr('fill', 'red')
.on('mouseover', mouseOverLogo)
.on('mouseout', mouseOutLogo);
var cir = g
.append('circle')
.attr('r', 30)
.attr('cx', 80)
.attr('cy', 80);
function mouseOverLogo() {
cir.transition()
.duration(2000)
.attr('transform', 'translate(0, 50)');
}
function mouseOutLogo() {
cir.transition()
.duration(2000)
.attr('transform', 'translate(0, -50');
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
<script src="https://d3js.org/d3.v6.js"></script>
</head>
<body>
<div class=fourGrid>
<div id=tl_grid>       
<svg id=languages></svg>
</div>
</div>
</body>
</html>

问题是,当您将鼠标悬停在圆形上时,您将不再在矩形上鼠标。圆圈会吸收鼠标的动作,而矩形不会留下任何内容。

因此,如果你把鼠标放在圆圈上,你要么不触发mouseover动作,要么触发,但立即触发mouseout动作,这会把圆圈放回原来的位置。

这里的解决方案是使圆圈不拦截任何鼠标事件,我们可以使用来做到这一点

cir.style("pointer-events","none"); 

如下所示:

const svg = d3.select('svg');
const width = svg.attr('width');
const height = svg.attr('height');
const g = svg
.append('g')
.attr('transform', `translate(${width / 2}, ${height / 2})`);
var cir_backboard = g
.append('rect')
.attr('x', 50)
.attr('y', 50)
.attr('width', 60)
.attr('height', 60)
.attr('fill', 'red')
.on('mouseover', mouseOverLogo)
.on('mouseout', mouseOutLogo);
var cir = g
.append('circle')
.attr('r', 30)
.attr('cx', 80)
.attr('cy', 80)
.style('pointer-events','none');
function mouseOverLogo() {
cir.transition()
.duration(2000)
.attr('transform', 'translate(0, 50)');
}
function mouseOutLogo() {
cir.transition()
.duration(2000)
.attr('transform', 'translate(0, -50');
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
<script src="https://d3js.org/d3.v6.js"></script>
</head>
<body>
<div class=fourGrid>
<div id=tl_grid>       
<svg id=languages></svg>
</div>
</div>
</body>
</html>

最新更新