admin管理员组

文章数量:1290981

Considering this example with 2 circles (red and blue):

<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).

Considering this example with 2 circles (red and blue):

<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).

Share Improve this question asked Mar 6, 2013 at 18:02 benjibenji 2,4518 gold badges41 silver badges66 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

See this 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);

http://jsfiddle/dKxZt/4/

It uses translate to move the element.

See this demo here to implement drag of an SVG element: Getting the Screen Pixel coordinates of a Rect element

It is the drag and drop SVG with JQuery Hope this link can help http://www.codedread./blog/archives/2005/12/21/how-to-enable-dragging-in-svg/

This is the demo http://www.codedread./dragtest.svg

本文标签: javascriptA generic JS function to move any SVG elementStack Overflow