开发者

Obtaining svg element 'id' attribute dynamically (Google SVG web)

开发者 https://www.devze.com 2023-01-05 19:05 出处:网络
(using http://code.google.com/p/svgweb/) window.onsvgload = function() { function onEnter(e) { var targ;

(using http://code.google.com/p/svgweb/)

window.onsvgload = function() {
  function onEnter(e) {          
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
      targ = targ.parentNode;

    alert(targ.hasAttributeNS(null, 'id')); //displays false
    alert(targ.getAttributeNS(null, 'id')); //displays a blank dialog
    alert(targ.id); //displays a blank dialog
  }

  /* Seldom_Seen is a group element in the SVG - <g id="Seldom_Seen">... */
  document.getEleme开发者_运维技巧ntById('Seldom_Seen').addEventListener("mouseover", onEnter, false); //alert is blank
  document.getElementById('normal_dom_element').addEventListener("mouseover", onEnter, false); //alert displays id as expected
}

The event listening works for SVG elements. I just can't seem to get the id. I can get other object properties like the x,y values. Anyway to get the ID of the targeted element?


maybe

e.currentTarget

but with jQuery, it is simply

window.onsvgload = function() {
  $('#Seldom_Seen').mouseover(function(){ onEnter(this); });
  $('#normal_dom_element').mouseover(function(){ onEnter(this); });
}

function onEnter(obj) {
  alert($(obj).attr("id"));
}


It's quite possible that you get another target than you expect. Do all your elements inside the 'Seldom_Seen' element have id's? You can always alert the target to see what type of element it is.

There are some gotchas with mouseover/mouseout on <g> elements too, the events bubble and you may get them twice unless you do some filtering. See slides 17 and 18 here for a possible workaround.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号