在 svg 中添加一个新行,bug 看不到该行 [英] add a new line in svg, bug cannot see the line

查看:14
本文介绍了在 svg 中添加一个新行,bug 看不到该行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 svg 中添加一个新行当按下添加按钮时,应在 svg 中添加一个新行我可以确定在元素中添加了该行,但为什么它没有显示在屏幕上?

I want to add a new line into the svg when, the add button is pressed, a new line should be added into the svg I can sure the line is added in the elements, but why it is not displayed on the screen?

<!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>

推荐答案

为了向 SVG 对象添加元素,必须在 SVG 命名空间中创建这些元素.由于 jQuery 目前不允许您执行此操作(AFAIK),因此您无法使用 jQuery 创建元素.这将起作用:

In order to add elements to an SVG object those elements have to be created in the SVG namespace. As jQuery doesn't allow you to do this at present (AFAIK) you can't use jQuery to create the element. This will work:

$("#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);
});

这是一个工作示例.

这篇关于在 svg 中添加一个新行,bug 看不到该行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆