【问题标题】:Not able to get SVG path - Snap.svg无法获取 SVG 路径 - Snap.svg
【发布时间】:2016-01-11 22:24:31
【问题描述】:

在当前的 init 函数中,我正在使用 Snap.load 加载 SVG,然后尝试获取该 SVG 的子“路径”元素;但是,路径函数在运行时会在控制台中输出“0”和“0”。已设置超时功能,但似乎仍无法识别任何“路径”元素。

如何才能让 SVG 的“路径”元素在脚本中输出?以下是当前 html 和脚本的示例。

HTML

在加载 SVG 资源之前:

<div class="icon-svg-morph" id="icon-svg">
    <svg class="animate-object icon-svg"></svg>
</div>

加载 SVG 资源后:

<div class="icon-svg-morph" id="icon-svg">
    <svg class="animate-object icon-svg" height="150" viewBox="0 0 500 500" width="150">
        <desc>Created with Snap</desc>
        <defs></defs>
        <path
            d="M345,230l-95-95l-95,95l-55,95l150,50l150-50L345,230z M250,334l-54.5-84L141,289
l31-52l78-75l78,75l31,52l-54.5-39L250,334z"
            id="icon-path"
            style="fill: #339ed9;"
        >
    </path>
    </svg>
</div>

JS

$.svgElement.prototype = {
    init: function() {
        var s = Snap('.icon-svg');

        Snap.load('asset/img/icon.svg', function (response) {
            var icon = response;
            s.append(icon);
        });

        s.attr({
            height: 150,
            viewBox: 0 + ' ' + 0 + ' ' + 500 + ' ' + 500,
            width: 150
        });

        this.path();
    },

    path: function() {
        var paths = $('.icon-svg').children('path');

        console.log(paths.length);

        if (! paths.length) {
            setTimeout(function(){
                console.log(paths.length);
            }, 100);

            return;
        }
    }
};

Click to view the current example.

【问题讨论】:

  • 不确定它会修复它,但至少我可以告诉你,如果你在超时后不更新paths,你的超时是没有用的。

标签: javascript jquery svg snap.svg


【解决方案1】:

如果你想要路径,我会使用 Snaps selectAll

s.selectAll('path') or s.select('path') 

如果你只想要一个,你可能需要确保选择可以访问 s。

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 2017-08-19
    • 1970-01-01
    • 2015-01-20
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多