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);
		});
	});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM