svg默认是新生成的元素在最顶层,有时候需要把新添加的放到底层(比如添加个背景图啥的),难道要先生成背景图然后在添加其他元素?那做功能太难了而且后期要改一个可能整个都要重画,偶然发现了用jquery的prepend方法可以实现,简单的测试代码:
<!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>