我希望能够缩放元素并将鼠标悬停在元素上。其中包括一个示例,后面是有关该场景的更多详细信息。
https://jsfiddle.net/pkerpedjiev/ny5ob3h2/4/
var svg = d3.select('svg')
var zoom = d3.behavior.zoom()
.on('zoom', draw)
svg.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', 400)
.attr('height', 400)
.attr('fill', 'transparent')
.call(zoom)
var xScale = d3.scale.linear()
.domain([0, 10])
.range([0,10])
zoom.x(xScale)
svg.append('text')
.attr('x', 50)
.attr('y', 100)
.text('Hi there')
.attr('visibility', 'hidden')
svg.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 10)
//.attr('pointer-events', 'none')
.on('mouseover', function(d) {
svg.selectAll('text')
.attr('visibility', 'visible');
})
.on('mouseout', function(d) {
svg.selectAll('text')
.attr('visibility', 'hidden')
});
function draw() {
d3.selectAll('circle')
.attr('r', xScale(10));
}
该示例仅包含一个圆圈和一些文本。除非鼠标位于圆圈上方,否则文本是不可见的。如果我使用鼠标滚轮滚动,圆圈的大小会根据缩放行为而变化。但是,如果鼠标位于圆圈上方,则缩放不起作用。
有办法解决这个问题吗?将圆圈上的 pointer-events
设置为 none
可以修复缩放,但不会调用 mouseover
事件。
有没有办法既调用圆的mouseover
,又能够在鼠标悬停在圆上时进行缩放?
最佳答案
是的,通过对圆进行缩放也可以实现这一点。
svg.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 10)
.call(zoom)//giving on circle also
//.attr('pointer-events', 'none')
.on('mouseover', function(d) {
svg.selectAll('text')
.attr('visibility', 'visible');
})
.on('mouseout', function(d) {
svg.selectAll('text')
.attr('visibility', 'hidden')
});
工作示例here
希望这有帮助!
编辑
如果您有很多元素,并且您不喜欢将缩放监听器附加到所有元素,那么您可以将缩放附加到包含所有内容的主组。
像这样:
var svg = d3.select('svg').attr("x",500).attr("y",500).append("g")
将缩放监听器附加到组。
svg.call(zoom);
工作代码here
关于javascript - 在 d3.js 中传播缩放事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34911465/