将SVG添加到HTML并处理事件

Add SVG to HTML and handle events

本文关键字:处理事件 HTML SVG 添加      更新时间:2023-09-26

我有这个SVG文件。显示不同的svg元素(Circle, Eclipse, Polygon,polyline等)

,每个元素都有自己的ID。

我可以添加函数(onClick或MouseClicK)当特定的ID被点击。

是否有任何方法来添加一个共同的函数(在JavaScript或Jquery)响应点击事件,并告诉我们从哪个对象(ID)点击起源?

所以我需要:

  1. HTML代码添加/引用SVG文件。不确定我是否使用SVG或对象标签?哪一个适用于所有浏览器?

  2. 然后JavaScript的JQuery响应鼠标点击元素并告诉哪个ID被点击了?

如果你看到下面的SVG,它有不同的圆圈,有ID,例如01,02,03等。

http://imgh.us/ClockControl.svg

最简单的方法是直接将svg打印到html中。这样,每个SVG元素都是DOM的"真正成员"。

<html>
    <head>
        …
    </head>
    <body>
        …
        <!-- 
           this stands for the content of »ClockControl.svg« 
           open it in a text editor, copy all the content, beginning at
           <svg and paste it into the html
        -->
        <svg id="your-svg">
            …
            <path id="e1" d="…" />
            …
        </svg>
    </body>
</html>

下一个是事件处理,可以这样做(on load):

var svg = document.querySelector('svg#your-svg'),
    handlers = {
        'e1' : function(e){ … }
    };
svg.addEventListener('click', function(e) {
    var c = e.target;
    while (c !== svg) {
        if (c.hasAttribute('id') {
            var id = c.getAttribute('id');
            if (handlers.hasOwnProperty(id)) {
                handlers[id](c);
                break;
            } 
        }
        c = c.parentNode;
    }
});

小提琴

如果您不熟悉SVG插入HTML的所有方法,请查看这里。这个答案中使用的方法叫做»inline SVG«。

您可以使用以下代码(只是没有使用jQuery的普通JavaScript),它将在页面中的每个SVG元素上添加一个事件侦听器click

document.querySelectorAll('svg').forEach(function(item){
item.addEventListener('click', function(event){alert('svg clicked was: ' + event.target.id)});
})
#circle{
  position:absolute;
}
#rect{
  position:absolute;
  left: 0;
  top: 100px;
  transform: translate(80px, 80px)
}
Click on one of the following SVG shapes.
<svg height="500" width="500">
  <circle id="circle"  cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
   <rect id="rect" width="100" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)">
  Sorry, your browser does not support inline SVG.
</svg>

可以使用jQuery获取id

$('svg').click(function(){
alert('element ID is: '+this.id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<svg id="1" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<svg id="2" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="blue" />
</svg>