2016-03-04 60 views
0

我有一個div工具提示,我希望以使用D3創建的SVG圓圈爲中心。我的mouseover事件觸發div的'隱藏'類爲false。查找由CSS隱藏的div的寬度

Plunker

因爲DIV是隱藏的,我無法計算它的寬度,我因此無法集中在圓股利的方式,我想:

var width = document.getElementById("tooltip").offsetWidth; 

... 

.style("left", xPosition - (width/2) + "px") 

是否有辦法我可以解決這個問題嗎?

它可能值得注意的是,我不希望該div有固定的寬度。

var w = 300, h = 500; 

var svg = d3.select('body').append('svg').attr('width', w).attr('height', h) 

svg.append('circle').attr('r', 20) 
    .attr('cx', 200) 
    .attr('cy', 300) 
    .on("mouseover", function(d) { 
    var xPosition = parseFloat(d3.select(this).attr("cx")); 
    var yPosition = parseFloat(d3.select(this).attr("cy")); 
    var width = document.getElementById("tooltip").offsetWidth; 

    d3.select("#tooltip") 
     .style("left", xPosition - (width/2) + "px") 
     .style("top", yPosition + "px") 
     .select("#value") 
     .text(d); 

    d3.select("#tooltip").classed("hidden", false); 
    }) 

    .on("mouseout", function() { 
    d3.select("#tooltip").classed("hidden", true); 
    }) 
+0

嗯,默認情況下它有'display:none',所以它沒有寬度。你可能不得不想一些其他的方法來隱藏div,比如說把它放在屏幕外面。 –

+0

'pos:rel; left:-50%'不起作用?我會避免使用JS ... – dandavis

+0

爲什麼不先讓它可見,然後放置它?我不認爲用戶會注意到跳 – tarulen

回答

3

您必須首先給div以外的顯示值「none」。然後你得到它的寬度。 然後你可以定位它。

如果不希望用戶看到DIV跳,給它的樣式visibility:hidden的,當你把它定位:

CSS:

.hidden { 
    display: none; 
    visibility: hidden; 
} 

JS:

d3.select("#tooltip").style("display", "block"); 
// your div is still invisible, but now has a width. 
// get its width and position it now 
d3.select("#tooltip").classed("hidden", false); // now it will appear 

如果再次隱藏,不要忘記重置display風格!

+0

非常感謝。你的回答非常明確,但我仍然無法解決這個問題。我第一次懸停時會返回一個不同的寬度連續盤旋,而且沒有任何焦點:https://plnkr.co/edit/CjoL2IlaLWgbG0FozD3o?p=info – user3821345