调整SVG foreignObject元素的大小以适合HTML元素

kar*_*tos 9 html size svg d3.js

我正在使用D3 javascript库进行可视化.我想为可视化的一些元素创建工具提示,而我的客户希望它们看起来像'纸片/后贴'.最初我使用一些不错的CSS技巧为工具提示创建了简单的DIV来创建所需的外观.(受本教程启发)

我想使用工具提示封装到SVG foreignObject-element中,因此它更适合可视化,我可以轻松地操作它们.(例如缩放/平移)所以我的问题是:如何获得DIV的正确大小,它位于foreignObject-element中,所以我可以准确地设置foreignObject-element的大小?特别是当使用margin/padding/shadow ....

我通过使用.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 + ')');
};
Run Code Online (Sandbox Code Playgroud)

这是一个有效的jsFiddle示例:http://jsfiddle.net/jhe8Y/1/

编辑:

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

所以我尝试了另一种方法,使用jQuerys .outerWidth(true)/.outerHeight(true)并手动计算阴影大小.这似乎工作得很好,但做这样的事情感觉非常糟糕.

有没有其他方法如何获得所有组件的DIV的确切大小?

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

adi*_*aya 0

我之前曾为此苦苦挣扎,我发现最简单的方法就是依靠Bootstrap 的 Tooltip

\n\n

例如

\n\n
// title: this is what gets shown as the title in the tooltip\nd3.select(\'svg\').attr(\'title\',\'This is my tooltip title\');\n\n// content: this will show up as the content if you go for \n// popovers instead . \nd3.select(\'svg\').attr(\'data-content\',\'This is some content\');\n\n// set the options \xe2\x80\x93 read more on the Bootstrap page linked to above\n$(\'svg\').popover({\n   \'trigger\':\'hover\'\n   ,\'container\': \'body\'\n   ,\'placement\': \'top\'\n   ,\'white-space\': \'nowrap\'\n   ,\'html\':\'true\' // preserve html formatting\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

它归结为,添加 titledata-content属性到您有兴趣添加工具提示的任何 svg 元素。然后,将内容设置为您想要的内容。所以,在你的情况下,html将是

\n\n
<div class=\'paper-tooltip\'>Lorem ipsum dolor sit amet, ... etc etc.</div>\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

有关的:

\n\n

如何使用 SVG 对象显示引导工具提示;关于堆栈溢出的问题

\n\n

引导工具提示

\n\n

我的超短博客文章

\n