HTML中的JavaScript和SVG [英] JavaScript and SVG in HTML

查看:95
本文介绍了HTML中的JavaScript和SVG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JavaScript文件. 我有SVG文件. 我也有HTML文件.

I have the JavaScript file. I have the SVG file. Also I have HTML file.

<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元素吗? (例如圆圈)

Anyone knows how I can call the element of SVG in JavaScript? (circle for example)

推荐答案

如果您想使用Javascript与加载到HTML5页面的svg文件进行动态交互,则必须以 inline .如果您加载为<object>,则无法使用JavaScript对其进行编程.但是,您可以通过XMLHttpRequest将svg文件加载为xml,并用响应填充DIV的innerHTML.然后可以通过Javascript动态更改此内联SVG.这适用于所有浏览器.试试下面的文件.

If you want to dynamically interact, using Javascript, with the svg file which is loaded into your HTML5 page, you must load the svg as inline. If you load as an <object> you cannot program it using your javascript. However you can load the svg file as xml via XMLHttpRequest and fill a DIV's innerHTML with the response. This inline SVG then can be dynamically changed via your Javascript. This works across all browsers. Try the files below.

假设您有一个SVG文件(my.svg)

Assume you have an SVG file(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文件如下:

and your HTML5 file is as below:

<!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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆