2013-08-20 104 views
9

我正在使用D3 JavaScript库进行可视化。我想为可视化的一些元素创建工具提示,而且我的客户希望它们看起来像是“纸片段/后处理”。最初,我使用一些漂亮的CSS技巧为工具提示创建了纯DIV,以创建所需的外观。 (灵感来自this tutorial调整SVG foreignObject元素的大小以适应HTML元素

我想使用封装工具提示到SVG foreignObject-element中,以便它更适合可视化,并且我可以轻松操纵它们。 (例如缩放/平移)所以我的问题是:如何获取位于foreignObject-element内的DIV的正确大小,以便我可以准确设置foreignObject-element的大小?特别是当使用保证金/填充/阴影....

我想通过使用.getBoundingClientRect(),但我不知道这是否是最好的方法。

这里是一个代码例如:

var body = d3.select("body"); 

var svg = body.append("svg"); 

var tooltipContainer = svg.append("svg:g"); 

var html = tooltipContainer.append("foreignObject") 
var div = html.append("xhtml:div") 
    .attr('class', 'paper-tooltip') 
    .html("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam.  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. Lorem ipsum  dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. Lorem ipsum dolor sit amet,  consectetur adipiscing elit. Donec eu enim quam. "); 

var bcr = div[0][0].getBoundingClientRect(); 

html.attr('x', 50) 
    .attr('y', 50) 
    .attr('width', bcr.width) 
    .attr('height', bcr.height); 

svg.call(d3.behavior.zoom().on('zoom', redrawOnZoom)); 

function redrawOnZoom(){ 
    tooltipContainer.attr('transform', 'translate(' + d3.event.translate + ')' + ' scale(' +   d3.event.scale + ')'); 
}; 

这里是一个工作的jsfiddle例如:http://jsfiddle.net/jhe8Y/1/

编辑:

我意识到,对于不同的阴影框设置.getBoundingClientRect ()将不起作用。我也意识到,用我的第一个解决方案.getBoundingClientRect()返回太大的尺寸,尤其是在正确的尺寸上。

所以我尝试了另一种方法,通过使用jQuerys .outerWidth(true)/。outerHeight(true)并手动计算阴影大小。这似乎工作正常,但感觉就像做这样的事情非常可怕。

是否有任何其他方式如何获得具有所有组件的DIV的确切大小?

更新的jsfiddle是在这里:http://jsfiddle.net/jhe8Y/3/

回答

0

我已经在此之前挣扎着,我发现,最容易做的事情是仅仅靠Bootstrap's Tooltip

E.g.

// title: this is what gets shown as the title in the tooltip 
d3.select('svg').attr('title','This is my tooltip title'); 

// content: this will show up as the content if you go for 
// popovers instead . 
d3.select('svg').attr('data-content','This is some content'); 

// set the options – read more on the Bootstrap page linked to above 
$('svg').popover({ 
    'trigger':'hover' 
    ,'container': 'body' 
    ,'placement': 'top' 
    ,'white-space': 'nowrap' 
    ,'html':'true' // preserve html formatting 
}); 

它归结为,增加titledata-content属性到任何SVG元素,你有兴趣加入tootltips来。然后,设置内容等于任何你想要的。所以,在你的情况下,html

<div class='paper-tooltip'>Lorem ipsum dolor sit amet, ... etc etc.</div> 

相关:

How do I show a bootstrap tooltip with an SVG object; Question on Stack Overflow

Bootstrap Tooltips

My super-short blog post on it

0

您不必将其放大并向下。没有真正的用处,对吧?然后,您可以将foreignObjectheightwidth设置为1,并通过CSS设置foreignObject { overflow: visible; }