svg结合js成为简单控件
正如标题所写,svg结合js可以成为一个简单的控件。在日常开发条状图的时候还是很方便的。
话不多说直接上代码。
test.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script type="text/javascript">
window.onload = function () {
//定义需要加载的宽度数据
var wids = [100,125,150,200];
var objs = document.querySelectorAll("object");
for (var i = 0; i < wids.length; ++i) {
//加载svg中的loadData函数
objs[i].contentWindow.loadData(wids[i]);
}
}
</script>
</head>
<body>
<div>
<div style="height: 10px">
<object data="testLoad.svg" type="image/svg+xml" width="300" height="10" ></object>
</div>
<div style="height: 10px">
<object data="testLoad.svg" type="image/svg+xml" width="300" height="10" ></object>
</div>
<div style="height: 10px">
<object data="testLoad.svg" type="image/svg+xml" width="300" height="10" ></object>
</div>
<div style="height: 10px">
<object data="testLoad.svg" type="image/svg+xml" width="300" height="10" ></object>
</div>
</div>
</body>
</html>
testLoad.svg
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect width="300" height="10" stroke="green" stroke-width="1" fill="yellow"></rect>
<script type="text/javascript" xlink:href="test.js"></script>
<script type="text/javascript">
function loadData(width){
document.querySelector("rect").style.width = width;
}
</script>
</svg>
将上面两个文件放入一个文件夹中,即可以根据设置的wids数据加载svg中loadData函数,来改变rect的宽度。
注:该页面需要在服务器环境中打开,否则会报类似于Uncaught DOMException: Blocked a frame with origin "null" from accessing
a cross-origin frame.这样的错误。