HTML 中的 JavaScript 和 SVG

标签 javascript html svg

<分区>

我有 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>

关于HTML 中的 JavaScript 和 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21815358/

相关文章:

javascript - AntD 自动完成下拉菜单默认打开焦点,我该如何防止它?

javascript - 如何在html中打印ajax、jquery、javascript中的数据?

javascript - 使用 Javascript 中的按钮执行 PHP 脚本

javascript - Bootstrap 4 导航栏第一个导航项未突出显示和 scrollspy 问题

javascript - 转换 svg :image to grayscale on click using d3

html - SVG 图案填充位置从右上角开始,而不是从左上角开始

javascript - ContentEditable 元素对热键没有反应

html - Internet Explorer 图像叠加链接

javascript - 从 DOM 中删除元素

jquery - 具有图案和图像元素的 SVG 转换为 PNG 图像失败