svg默認(rèn)是新生成的元素在最頂層憨降,有時(shí)候需要把新添加的放到底層(比如添加個(gè)背景圖啥的),難道要先生成背景圖然后在添加其他元素?那做功能太難了而且后期要改一個(gè)可能整個(gè)都要重畫,偶然發(fā)現(xiàn)了用jquery的prepend方法可以實(shí)現(xiàn)吏奸,簡(jiǎn)單的測(cè)試代碼:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
? ? <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
? ? <title></title>
? ? <script src="jquery-3.2.1.js"></script>
? ? <script type="text/javascript">
? ? ? ? var svgimg
? ? ? ? function test() {
? ? ? ? ? ? $("#svg1").empty();
? ? ? ? ? ? svgimg = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
? ? ? ? ? ? svgimg.setAttribute('height', '200');
? ? ? ? ? ? svgimg.setAttribute('width', '200');
? ? ? ? ? ? svgimg.setAttribute('x', '0');
? ? ? ? ? ? svgimg.setAttribute('y', '0');
? ? ? ? ? ? svgimg.setAttribute('points', "0,100 100,0 200,100 100,200")
? ? ? ? ? ? svgimg.setAttribute('style', "fill:red;stroke:#000000;stroke-width:1;")
? ? ? ? ? ? document.getElementById('svg1').appendChild(svgimg);
? ? ? ? ? ? svgimg = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
? ? ? ? ? ? svgimg.setAttribute('height', '200');
? ? ? ? ? ? svgimg.setAttribute('width', '200');
? ? ? ? ? ? svgimg.setAttribute('x', '0');
? ? ? ? ? ? svgimg.setAttribute('y', '0');
? ? ? ? ? ? svgimg.setAttribute('points', "50,100 150,0 250,100 150,200")
? ? ? ? ? ? svgimg.setAttribute('style', "fill:green;stroke:#000000;stroke-width:1;")
? ? ? ? ? ? document.getElementById('svg1').appendChild(svgimg);
? ? ? ? ? ? svgimg = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
? ? ? ? ? ? svgimg.setAttribute('height', '200');
? ? ? ? ? ? svgimg.setAttribute('width', '200');
? ? ? ? ? ? svgimg.setAttribute('x', '0');
? ? ? ? ? ? svgimg.setAttribute('y', '0');
? ? ? ? ? ? svgimg.setAttribute('points', "100,100 200,0 300,100 200,200")
? ? ? ? ? ? svgimg.setAttribute('style', "fill:blue;stroke:#000000;stroke-width:1;")
? ? ? ? ? ? document.getElementById('svg1').appendChild(svgimg);
? ? ? ? }
? ? ? ? function bb() {
? ? ? ? ? ? $("#svg1").prepend($("polygon")[2]);
? ? ? ? }
? ? </script>
</head>
<body>
? ? <button onclick="test();">添加菱形</button>
? ? <input type="button" onclick="bb()" value="把最上層置為底層" />
? ? <svg id="svg1" width="600" height="600" viewBox="0 0 600 600"
? ? ? ? xmlns="http://www.w3.org/2000/svg"
? ? ? ? xmlns:xlink="http://www.w3.org/1999/xlink">
? ? </svg>
</body>
</html>