Svg-interactivity

提供:Dev Guides
移動先:案内検索

SVG-双方向性

SVG画像は、ユーザーのアクションに応答するようにできます。 SVGは、ポインターイベント、キーボードイベント、およびドキュメントイベントをサポートしています。 次の例を考えてください。

テストVG

<html>
   <title>SVG Interactivity</title>
   <body>

      <h1>Sample Interactivity</h1>

      <svg width="600" height="600">
         <script type="text/JavaScript">
            <![CDATA[
               function showColor() {
                  alert("Color of the Rectangle is: "+
                  document.getElementById("rect1").getAttributeNS(null,"fill"));
               }

               function showArea(event){
                  var width = parseFloat(event.target.getAttributeNS(null,"width"));
                  var height = parseFloat(event.target.getAttributeNS(null,"height"));
                  alert("Area of the rectangle is: " +width +"x"+ height);
               }

               function showRootChildrenCount() {
                  alert("Total Children: "+document.documentElement.childNodes.length);
               }
            ]]>
         </script>

         <g>
            <text x="30" y="50" onClick="showColor()">Click me to show rectangle color.</text>

            <rect id="rect1" x="100" y="100" width="200" height="200"
            stroke="green" stroke-width="3" fill="red"
            onClick="showArea(event)"/>

            <text x="30" y="400" onClick="showRootChildrenCount()">
            Click me to print child node count.</text>
         </g>
      </svg>

   </body>
</html>

説明

  • SVGはJavaScript/ECMAScript関数をサポートしています。 スクリプトブロックはCDATAブロックにあり、XMLでの文字データのサポートを考慮します。
  • SVG要素は、マウスイベント、キーボードイベントをサポートします。 onClickイベントを使用して、javascript関数を呼び出しました。
  • javascript関数では、documentはSVGドキュメントを表し、SVG要素を取得するために使用できます。
  • JavaScript関数では、イベントは現在のイベントを表し、イベントが発生したターゲット要素を取得するために使用できます。

出力

ChromeウェブブラウザでテキストSVGを開きます。 Chrome/Firefox/Operaを使用して、プラグインなしでSVG画像を直接表示できます。 Internet Explorer 9以降もSVG画像レンダリングをサポートしています。 各テキストと長方形をクリックして、結果を確認します。