2016-01-20 93 views
0

我希望能夠縮放和鼠標懸停元素。包括一個例子,後面跟着更多關於這個場景的細節。在d3.js中傳播縮放事件

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-eventsnone修復縮放,但不會調用mouseover事件。

有沒有辦法讓圓圈的mouseover被調用,並且能夠在鼠標移過圓的時候進行縮放?

回答

1

是的,這也可以通過在圓上放大縮小來實現。

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

+0

它不只是一個圓圈,但很多在上面的東西呢?是否有可能處理每個元素的事件,然後讓底部元素處理縮放或者最頂層的元素是否總是必須處理縮放? –

+0

如果您有太多的圈子,而且您不想將所有人的監聽連接到上面,請閱讀我的**編輯**部分。 – Cyril