2017-06-05 92 views
1

我想開發一個交互式的SVG地圖,當鼠標進入SVG圖像的矩形時,我想做些東西。目前,當我的鼠標進入SVG圖像時,代碼會記錄到控制檯,但當我將鼠標懸停在矩形上時,則不會。任何幫助將非常感激。謝謝!Javascript SVG Interaction Issue

<object onload="svgOnLoad()" id="activeSVG" data="SVGNAME.svg" type="image/svg+xml"> 
 
</object> 
 

 
    <script> 
 
      function svgOnLoad() { 
 
       console.log("SVG Loaded"); 
 
       $("#activeSVG").mouseenter(function(e) { 
 
       console.log("In the SVG") 
 
       }); 
 

 
       //Executed when the mouse enters an SVG rect element 
 
       $("rect").mouseenter(function(e) { 
 
       console.log("Mouse Entered rectangles!!") 
 
       }); 
 
      } 
 
    </script>

回答

0

亂搞與它一點我發現了什麼需要添加後。你需要獲得svg對象的內容,然後從那裏玩它。我已經在下面包含了新的腳本代碼。

<script> 
 
      function svgOnLoad() { 
 
       // Get SVG object 
 
       var officeMapFloor = document.getElementById("activeSVG"); 
 

 
       // Get the content of the SVG object 
 
       var svgDoc = officeMapFloor.contentDocument; 
 

 
       // Access an ID within the content of the object 
 
       var rect = svgDoc.getElementById("siesta"); 
 

 
       // Apply the event listener 
 
       rect.onmouseover = function(){ 
 
       console.log("Finally in the rectangle"); 
 
       }; 
 

 
      } 
 
</script>

0

有一簡短的描述,例如,在https://www.tutorialspoint.com/svg/svg_interactivity.htm

對於mouseover事件,你需要jQuerymouseover功能:https://api.jquery.com/mouseover/

+0

對,我知道,我需要最終改變的情況下,但它不記錄任何一種方式。當我輸入矩形時它仍然應該記錄,但它現在不是。 –

+0

嘗試將代碼放在'document.ready()'函數中。也許,事件的註冊是在SVG完全加載之前完成的。 – Guybrush

+0

但它被稱爲onload後準備好了,所以我不認爲這是問題 –