2015-10-21 20 views
0

我對svg's很新,並且向它添加了javascript。我可以添加一個函數到css部分的svg多邊形嗎?

我試圖生成通過CSS部分獲取所有功能的圖表。現在我喜歡的功能添加到不同的對象,但我甚至不知道這是可能的,像我一樣在我的例子,因爲它是不工作:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11,dtd"> 
<svg width="9668pt" height="2132pt" viewBox=0.00 0.00 9668.29 2132.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
    <defs> 
    <style type="text/css"><![CDATA[ 
     .node:hover polygon { stroke: yellow; fill: yellow; onclick:'myFunc(evt)';} 
     .node: polygon { stroke: yellow; fill: yellow; onclick:'myFunc(evt)';} 
    ]]></style> 
    <script type="text/javascript"><![CDATA[ 
     function myFunc(evt) { 
     //do sth... 
     } 
    ]]></script> 
    </defs> 
    <g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 2128)"> 
    <title>MyTest</title> 
    <polygon fill="white" stroke="none" points="-4,4 -4,-2128 9664.29,-2128 9664.29,4 -4,4"/> 
    <g id="myTestNode" class="node"> 
     <title>Box</title> 
     <polygon points="7270.09,2124 7208.09,-2124 7208.09,-2088 7270.09,-2088 7270.09,-2124"> 
    </g> 
    </g> 
</svg> 

有沒有人有一個想法如何使這項工作,除了將onclick=myFunc(evt)添加到每個多邊形?

回答

0

不,這是行不通的。 CSS僅用於演示文稿。有很多方法可以使用CSS選擇器來附加行爲。最低級別是querySelector和querySelectorAll。恕我直言,最簡單和最常用的是jQuery。

這裏承諾是片段...

$("rect").hover(function(event) { 
 
    $("#out1").text("hover: " + event.target.getAttribute("class")) 
 
}) 
 
$(".same").click(function(event) { 
 
    $("#out1").text("click: " + event.target.getAttribute("class")) 
 
}) 
 
$(".other").click(function(event) { 
 
    $("#out1").text("some other element was clicked") 
 
})
.one { 
 
    fill: red 
 
} 
 
.two { 
 
    fill: green 
 
} 
 
.three { 
 
    fill: blue 
 
} 
 
.four { 
 
    fill: yellow 
 
} 
 
rect:hover { 
 
    fill: orange; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<svg viewBox="0 0 100 100" width="200" height="200"> 
 
    <rect class="one same" x="0" y="0" width="50" height="50" /> 
 
    <rect class="two same" x="50" y="0" width="50" height="50" /> 
 
    <rect class="three other" x="0" y="50" width="50" height="50" /> 
 
    <rect class="four none" x="50" y="50" width="50" height="50" /> 
 
</svg> 
 

 
<div id="out1"></div>

+0

大,感謝信息。期待您的片段。 – Metalinjection

相關問題