鍍金池/ 教程/ HTML/ SVG交互
SVG鏈接
SVG陰影效果
SVG線性漸變
SVG文本
SVG平面陰影
SVG圖表
SVG交互
SVG時(shí)鐘
SVG漸變
SVG <pattern>元素
SVG簡(jiǎn)介
SVG徑向漸變
SVG <filter>元素
SVG對(duì)話框效果
SVG形狀
SVG stroke屬性
SVG圖形
SVG教程
SVG事件監(jiān)聽器
SVG加載器示例
SVG腳本(JavaScript)
SVG圖標(biāo)
SVG拖動(dòng)
SVG模糊效果

SVG交互

SVG圖像可以響應(yīng)用戶的操作。 SVG支持指針事件,鍵盤事件和文檔事件??纯聪旅娴睦印?/p>

實(shí)例

文件:testSVG.html -

<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函數(shù)。腳本塊是在CDATA塊中考慮XML中的字符數(shù)據(jù)支持。
  • SVG元素支持鼠標(biāo)事件,鍵盤事件。使用onClick事件來調(diào)用javascript函數(shù)。
  • 在javascript函數(shù)中,文檔表示SVG文檔,可用于獲取SVG元素。
  • 在javascript函數(shù)中,1event1表示當(dāng)前事件,可用于獲取引發(fā)事件的目標(biāo)元素。

在Chrome瀏覽器中打開文件:textSVG.html ,得到以下結(jié)果 -

點(diǎn)擊上面圖片可以提示子節(jié)點(diǎn)數(shù)。


上一篇:SVG圖形下一篇:SVG事件監(jiān)聽器