gpt4 book ai didi

javascript - 通过 JavaScript 或 JQuery 操作 SVG 文件(对象)中的元素

转载 作者:行者123 更新时间:2023-11-29 18:07:48 26 4
gpt4 key购买 nike

我遇到了在 html 代码中操作 SVG 文件(对象)的挑战。 Snap、Raphael 中有解决方案,但我需要直接通过 JavaScript 或 JQuery 来完成。这就是我到目前为止所拥有的:

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>

谢谢!!!

最佳答案

通常,当我想单独通过 javascript 创建或操作 SVG 图形时,我会使用 D3.js 库。 http://d3js.org/

与像 Raphaeljs 这样的 polyfill 库不同,D3 提供了一个 javascript API,用于在浏览器中实时直接操作 SVG 元素。

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)

例如,这是我根据 D3 教程制作的演示,该演示使用 Javascript native new Date() 构建和操作 SVG 元素以创建实时 javascript/svg 驱动时钟功能:http://jsfiddle.net/2jogwx6x/1/

D3.js 策略可能适用于您的目的,元素选择方法类似于 jQuery 的 CSS 选择方法,但直接使用 dom 节点,但要使其起作用,您需要将 SVG 数据直接嵌入到 DOM 中喜欢:

<!-- 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>

而不是使用 <object id="testSVG" data="image_library/grandstaff_drawing_only.svg" type="image/svg+xml" height=100% width=100%">

要在 DOM 中动态操作 SVG 数据,它必须是 DOM 的一部分,而不是打开/写入/关闭外部文件。

关于javascript - 通过 JavaScript 或 JQuery 操作 SVG 文件(对象)中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30005163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com