我想在svg中添加一个新行,当按下添加按钮时,应该在svg中添加一个新行我可以确定该行添加在元素中,但为什么它不显示在屏幕上?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#map
{
border:1px solid #000;
}
line
{
stroke:rgb(0,0,0);
stroke-width:3;
}
</style>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#add").click(function(){
var newLine=$('<line id="line2" x1="0" y1="0" x2="300" y2="300" />');
$("#map").append(newLine);
});
})
</script>
</head>
<body>
<h2 id="status">
0, 0
</h2>
<svg id="map" width="800" height="600" version="1.1" xmlns="http://www.w3.org/2000/svg">
<line id="line" x1="50" y1="0" x2="200" y2="300"/>
</svg>
<button id="add">add</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
rob*_*rtc 33
为了向SVG对象添加元素,必须在SVG名称空间中创建这些元素.由于jQuery目前不允许你这样做(AFAIK),你不能使用jQuery来创建元素.这将有效:
$("#add").click(function(){
var newLine = document.createElementNS('http://www.w3.org/2000/svg','line');
newLine.setAttribute('id','line2');
newLine.setAttribute('x1','0');
newLine.setAttribute('y1','0');
newLine.setAttribute('x2','300');
newLine.setAttribute('y2','300');
$("#map").append(newLine);
});
Run Code Online (Sandbox Code Playgroud)
代码少一点
$("#add").click(function(){
$(document.createElementNS('http://www.w3.org/2000/svg','line')).attr({
id:"line2",
x1:0,
y1:0,
x2:300,
y2:300
}).appendTo("#map");
});
Run Code Online (Sandbox Code Playgroud)