SVG 动态添加元素与事件


SVG文件是由各个元素组成。元素由标签定义,而标签格式即html的元素定义格式。但是载入一个SVG文件,却无法通过常规的js获取对象方式来获取到SVG中定义的元素,更无法通过这种方式来动态添加SVG元素与事件。 SVG元素的操作都要借助于SVG的document对象。SVG的document对象获取方式为:
SVG 快速入门


svgDoc = document.getElementById("mySVG").getSVGDocument();其中mySVG为SVG主体的id。注意需要在SVG完全加载完成后才可获取,否则获取到的是null。
然后调用svgDoc. createElementNS()函数即可创建SVG元素,为创建的元素进行属性设置,
并绑定事件监听器。最后调用svgDoc.rootElement.appendChild()函数来将创建的元素添加给svgDoc。


示例代码:


<embed id="mySVG" src="map.svg" type="image/svg+xml" />
<div>x坐标值<input id="xValue"></div>
<div>y坐标值<input id="yValue"></div>
<div>文本内容<input id="iText"></div>
<button id="add">动态添加元素</button>
 
<script>
	var svgDoc = null;
	var time = null;
 
	// 动态添加元素
	var addElement = function(x, y, nodeText) {
		// 添加圆形
		var c = svgDoc.createElementNS('http://www.w3.org/2000/svg', 'circle');
		c.setAttribute('cx', x);
		c.setAttribute('cy', y);
		c.r.baseVal.value = 7;
		c.setAttribute('fill', 'red');
		c.addEventListener("click", function() {
			alert('圆形点击测试:' + nodeText);
		});
		c.addEventListener("mouseover", function() {
			console.log('圆形鼠标悬停测试:' + nodeText);
		});
		svgDoc.rootElement.appendChild(c);
 
		// 添加文本
		var t = svgDoc.createElementNS('http://www.w3.org/2000/svg', 'text');
		t.setAttribute("x", parseInt(x) + 5);
		t.setAttribute("y", parseInt(y) + 10);
		t.setAttribute("font-size", "20");
		t.setAttribute('fill', 'green');
		t.addEventListener("click", function() {
			alert('文本点击测试:' + nodeText);
		});
		t.addEventListener("mouseover", function() {
			console.log('文本鼠标悬停测试:' + nodeText);
		});
		t.innerHTML = nodeText;
		svgDoc.rootElement.appendChild(t);
	};
 
	// 载入SVG
	var loadSvg = function() {
		svgDoc = document.getElementById("mySVG").getSVGDocument();
		if(svgDoc == null) {
			time = setTimeout("loadSvg()", 300);
		} else {
			clearTimeout(time);
			loadCallback();
		}
	};
 
	// 载入回调
	var loadCallback = function() {
		console.log("加载完成");
	};
 
	$(function() {
		// 延迟加载
		setTimeout("loadSvg()", 300);
 
		// 按钮
		$("#add").click(function() {
			var nodeText = $("#iText").val();
			if(nodeText == "") {
				nodeText = "未输入文本";
			}
			console.log(nodeText);
			addElement($("#xValue").val(), $("#yValue").val(), nodeText);
		});
	});

原文地址:https://www.cnblogs.com/lovellll/p/10208207.html