jQuery添加的svg元素没有显示出来 [英] jQuery-added svg elements do not show up

查看:357
本文介绍了jQuery添加的svg元素没有显示出来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果已经回答了这个问题,我是SO的新手。

Sorry if this has already been answered, I am new to SO.

我正在尝试使用jquery创建svg元素,并且我将此代码作为HTML页面:

I am trying to create svg elements using jquery, and I have this code as part of an HTML page:

<svg viewBox="0 0 1000 500">
    <defs>
        <clipPath id="clip">
            <ellipse cx="100" cy="250" rx="200" ry="50" />
        </clipPath>
    </defs>
    <g>
        <path d="M 0,0 L 1000,0 1000,500 0,500"
            fill="#9ADEFF" />
        <path id="boat" stroke="none" fill="red"
            d="M 100,175 L 300,175 300,325 100,325"
            clip-path="url(#clip)" />
    </g>
    <g id="0002" width="100" height="100%"
        transform="translate(1000)">
        <line x1="50" y1="0" x2="50" y2="300"
            stroke="green" stroke-width="100" />
    </g>
</svg>

和这个Javascript(使用jQuery 1.9):

and this Javascript (with jQuery 1.9):

var id = 10000,
    coinArray = []

function generateNextLine(type) {
    $('svg').append($(type()))
    return $('svg')[0]
}

function idNo() {
    id++
    return ((id-1)+"").substr(-4)
}

function random(x,y) {
    if (!y) {
        y=x
        x=0
    }
    x=parseInt(x)
    y=parseInt(y)
    return (Math.floor(Math.random()*(y-x+1))+x)
}

function coins() {
    coinArray[id%10000]=[]
    var gID = idNo(), x,
    g=$(document.createElement('g')).attr({
        id: gID,
        width: "100",
        height: "100%"
    })
    while (3<=random(10)) {
        var randomPos=random(50,450)
        coinArray[(id-1)%10000][x] = randomPos
        $(g).append(
            $(document.createElement('circle'))
            .attr({
                cx: "50",
                cy: randomPos,
                r: "50",
                fill: "yellow"
            })
        )
        x++
    }
    return $(g)[0]
}

当我运行 generateNextLine(coins); 时,svg添加了这个元素:

When I run generateNextLine(coins);, the svg adds this element:

<g id="0000" width="100" height="100%">
    <circle cx="50" cy="90" r="50" fill="yellow"></circle>
</g>

但是,svg的实际显示不会改变。如果我将此代码直接添加到svg,它会像我期望的那样呈现,但运行我的javascript函数似乎对显示没有任何作用。我在OS X Lion上使用Chrome 28。

However, the actual display of the svg doesn't change. If I add this code directly to the svg, it renders as I would expect, but running my javascript function does not seem to do anything to the display. I am using Chrome 28, on OS X Lion.

推荐答案

您必须在SVG命名空间中创建SVG元素,这意味着您可以' t do

You must create SVG elements in the SVG namespace which means you can't do

document.createElement('g')

但你必须写

document.createElementNS('http://www.w3.org/2000/svg', 'g')

同样适用于圈子等。

这篇关于jQuery添加的svg元素没有显示出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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