【解決方法】 タグ内の Jquery select SVG 要素

プログラミングQA


ボタンのクリックで変化するいくつかの linearGradient 要素を持つ SVG があります。ここでわかるように、すべて正常に動作します。 編集フィドル – JSFiddle[^]

私の質問は、私の例の svg が外部ファイルであり、 タグで呼び出された場合、どうすれば同じことができるでしょうか?

私が試したこと:

私のsvg画像:

HTML
<object data="Img/PumpStation/Pump.svg" type="image/svg+xml" id="alphasvg1111"></object>

私のボタン:

ASP.NET
<asp:Button ID="Button1" class="test" runat="server" Text="Button" />

私のjQuery関数:

JavaScript
jQuery('.test').on('click', function () {
    //$("object").contents().find("path").attr({ "fill": "red" });
    jQuery('object stop').each(function () {
        var color = jQuery(this).css('stop-color');
        if (color === 'rgb(77, 77, 77)') {
            jQuery(this).css('stop-color', '#ff0000');
        }
    });
});

私が使用する場合:

JavaScript
$("object").contents().find("path").attr({ "fill": "red" });

、ボタンをクリックすると SVG が赤くなります。 残りの機能が機能しないのはなぜですか?

解決策 1

<object> 要素は、同様の方法で別のドキュメントを作成します <iframe>.

同じドメインからのものであるため、次を使用してそのドキュメントにアクセスできます jQueryの contents 方法[^]. ただし、最上位ドキュメントに対して実行される jQuery セレクターは、ネストされたドキュメント内の要素を選択できません。

jQuery("object stop") はゼロの一致を返します。 stop は現在のドキュメントの一部ではありません。 しかし jQuery("object").contents().find("stop") 動作するはずです。

JavaScript
jQuery('.test').on('click', function () {
    jQuery('object').contents().find('stop').each(function () {
        var color = jQuery(this).css('stop-color');
        if (color === 'rgb(77, 77, 77)') {
            jQuery(this).css('stop-color', '#ff0000');
        }
    });
});

解決策 2

<object data="Img/PumpStation/Pump.svg" type="image/svg+xml" id="alphasvg1111"></object>

コメント

タイトルとURLをコピーしました