我有 JavaScript 文件。
我有 SVG 文件。
我还有 HTML 文件。
<head>
...
<link rel="stylesheet" href="style.css" type="text/css" charset="utf-8">
...
</head>
<body>
...
<img src='svgfile.svg' type='image/svg+xml' />
...
</body>
有人知道如何在 JavaScript 中调用 SVG 元素吗? (以圆圈为例)
如果您想使用 Javascript 与加载到您的 HTML5 页面中的 svg 文件进行动态交互,您必须将 svg 加载为内联。如果您加载为 <object>
你不能使用你的 javascript 来编程。但是,您可以通过 XMLHttpRequest
将 svg 文件加载为 xml并填写 DIV 的 innerHTML
与响应。然后可以通过您的 Javascript 动态更改此内联 SVG。这适用于所有浏览器。试试下面的文件。
假设你有一个 SVG 文件(my.svg)
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">
<circle id="myCircle" cx="200" cy="200" fill="blue" r="150" />
</svg>
您的 HTML5 文件如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<div id="svgInlineDiv" style='background-color:lightgreen;width:400px;height:400px;'></div>
<button onClick=changeInlineCircleColor()>Change Circle Color</button>
<div id="svgObjectDiv" style='background-color:lightblue;width:400px;height:400px;'>
<object data="my.svg" type="image/svg+xml" id="objsvg" width="100%" height="100%"></object>
</div>
</center>
<script id=myScript>
function changeInlineCircleColor()
{
myCircle.setAttribute("fill","red")
}
</script>
<script>
document.addEventListener("onload",inlineSVG(),false)
function inlineSVG()
{
var SVGFile="my.svg"
var loadXML = new XMLHttpRequest;
function handler(){
if(loadXML.readyState == 4 && loadXML.status == 200)
svgInlineDiv.innerHTML=loadXML.responseText
}
if (loadXML != null){
loadXML.open("GET", SVGFile, true);
loadXML.onreadystatechange = handler;
loadXML.send();
}
}
</script>
</body>
</html>