【发布时间】:2012-09-19 11:48:44
【问题描述】:
我的元素定位有问题。我有一个 div 元素,它还包含 svg path 元素。标记是这样的:
<div style="position:absolute;" class="svg">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<path id="path203" d="M150 0 L75 200 L225 200 Z" />
</svg>
</div>
当用户将鼠标悬停在路径上时,我想在路径元素周围设置边框。为此,我必须访问路径元素的高度和重量,然后将这些值设置为其父 div 元素的高度和宽度。为此,我使用了 getBoundingClientRect()。代码:
var box = document.getElementById("path203").getBoundingClientRect();
$("#path203").parents("div.svg").css({ width: box.width + "px", height: box.height + "px" });
这里我的问题并没有完全解决,我只得到了边框,但是 div 的位置和它的子路径元素是不一样的,它们都有不同的偏移值。所以为此我也为父 div 设置了顶部和左侧:
var box = document.getElementById("path203").getBoundingClientRect();
$("#path203").parents("div.svg").offset({ left: box.left + "px", top: box.top });
现在这个 div 得到了正确的位置,但是它的子路径元素从它的位置移开了。可能是因为 path 元素是 div 元素的子元素。所以当我们移动 div 时,它的所有子元素也会同时移动。如何在不更改其子元素偏移量的情况下更改父 div 偏移量值?
【问题讨论】:
标签: javascript jquery svg