SVG - 互動性



SVG 影像可以對使用者的操作做出響應。SVG 支援指標事件、鍵盤事件和文件事件。請考慮以下示例。

示例

testSVG.htm
<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 函式中,event 代表當前事件,可用於獲取發生事件的目標元素。

輸出

在 Chrome 瀏覽器中開啟 textSVG.htm。您可以使用 Chrome/Firefox/Opera 直接檢視 SVG 影像,無需任何外掛。Internet Explorer 9 及更高版本也支援 SVG 影像渲染。點選每個文字和矩形以檢視結果。

廣告