2017-06-05 93 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后准备好了,所以我不认为这是问题 –