javascript 移动任何 SVG 元素的通用 JS 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15254659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A generic JS function to move any SVG element
提问by benji
Considering this example with 2 circles (red and blue):
考虑这个有 2 个圆圈(红色和蓝色)的例子:
<svg width="500px" height="500px">
<circle cx="100" cy="50" r="40" fill="red" id="redcircle" />
<g transform="translate(200,-20)">
<g transform="scale(2)">
<g transform="rotate(45)">
<g transform="translate(5,10)">
<circle cx="100" cy="50" r="40" fill="blue" id="bluecircle" />
</g>
</g>
</g>
</g>
</svg>
I wonder if there is a way to write a generic function like:
我想知道是否有一种方法可以编写一个通用函数,例如:
function move(selection){
// ???
}
That would allow to write move("#redcircle")
or move("#bluecircle")
which would visually move the target element 100px to the right (for example).
这将允许写入move("#redcircle")
或move("#bluecircle")
将目标元素向右移动 100 像素(例如)。
回答by Matthias
See this jsfiddle
看到这个jsfiddle
function moveSection(idStr, xOffset, yOffset) {
var domElemnt = document.getElementById(idStr);
if (domElemnt) {
var transformAttr = ' translate(' + xOffset + ',' + yOffset + ')';
domElemnt.setAttribute('transform', transformAttr);
}
}
moveSection("bluecircle", 50, 20);
It uses translate to move the element.
它使用 translate 来移动元素。
See this demo here to implement drag of an SVG element: Getting the Screen Pixel coordinates of a Rect element
在此处查看此演示以实现 SVG 元素的拖动:获取 Rect 元素的屏幕像素坐标
回答by giaosucan
It is the drag and drop SVG with JQuery Hope this link can help http://www.codedread.com/blog/archives/2005/12/21/how-to-enable-dragging-in-svg/
它是带有 JQuery 的拖放 SVG 希望此链接可以帮助 http://www.codedread.com/blog/archives/2005/12/21/how-to-enable-dragging-in-svg/
This is the demo http://www.codedread.com/dragtest.svg