简体   繁体   中英

Manipulate elements in SVG file (object) by JavaScript or JQuery

I have a challenge of manipulating SVG file (object) in html code. There are solutions in Snap, Raphael but I need to do it directly by either JavaScript or JQuery. That's what I have so far:

JS:

<object id="testSVG" data="image_library/grandstaff_drawing_only.svg"       
type="image/svg+xml" height=100% width=100%">
<img src="image_library/alto-clef.png" />
</object>

 <script>

window.onload=function() {
// Get the Object by ID
var a = document.getElementById("testSVG");
// Get the SVG document inside the Object tag
var svgDoc = a.contentDocument;
// Get one of the SVG items by ID;
var svgItem = svgDoc.getElementById("path3380");
// Set the colour to something else
//svgItem.setAttribute("stroke", "red");
svgItem.style.stroke = "#ff0000";
};

</script>

JQuery:

<object id="testSVG" data="image_library/grandstaff_drawing_only.svg"    
type="image/svg+xml" height=100% width=100%">
<img src="image_library/alto-clef.png" />
</object>


<script>

window.onload=function() {
var svgDoc = $(“#testSVG”)[0].contentDocument; 
$(“#path3380”, svgDoc).css(“stroke”, “red”); 

};

</script>

Thank you!!!

Normally I use D3.js library when I want to create or manipulate SVG graphics by javascript alone. http://d3js.org/

Unlike libs like Raphaeljs, which polyfills, D3 provides a javascript API for direct manipulation of SVG elements within the browser in real time.

D3 is Not a SVG Polyfill: Unlike Raphaël, which provides polyfill for SVG on browsers that do not support SVG. D3 manipulates SVG directly, without any abstraction layer. Your browser needs to support SVG for D3 to work properly. ( source )

For example, here's a demo I made from a D3 tutorial that constructs and manipulates SVG elements to create a live javascript / svg driven clock using the Javascript native new Date() function: http://jsfiddle.net/2jogwx6x/1/

The D3.js strategy will likely work for your purposes and the elem selection method is similar to jQuery's CSS selection method but working directly with dom nodes, but for it to work you would need to directly embed your SVG data into the DOM like:

<!-- simple rectangle - replace this with your real svg data -->
<svg width="400" height="110">
    <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)">
</svg>

Instead of using <object id="testSVG" data="image_library/grandstaff_drawing_only.svg" type="image/svg+xml" height=100% width=100%">

To manipulate SVG data in the DOM on the fly it has to be a part of the DOM and not opening / writing to / closing an external file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM