0

I am using the object tag to embed svg's. I'd like to be able to set click events as well as changing things like the fill color on mouseover and mouseout. I understand that I can set the events from within the svg, but its very impractical when the svg is part of a navigation system etc.

<a id="{{id}}DatePickerBtn">
    <object data="images/date-icon.svg" type="image/svg+xml" style="height: 100%;"></object>
    <span class="block">Change Date</span>
</a>

Setting an event on the 'a' tag only fires when the span text is clicked, setting the event on the btn.getElementsByTagName('object')[0] doesn't work either.

I've scoured the internet looking for tutorials on interacting with svg's from javascript with no luck. Please no jQuery, I prefer vanilla JS.

4

2 に答える 2

1

You could make a transparent div overlay in order to capture all mouse events.

<div style="margin: 0px; padding: 0px; position: absolute; width: 100px; height: 100px; background-color: rgba(128, 128, 128, 0.0);" id="clickableDiv"></div>

To find any pixel coordinates of an SVG element you could use these two functions

    ...getScreenCTM();
    matrixTransform(...);

Any details can be found here: Getting the Screen Pixel coordinates of a Rect element

于 2013-02-11T17:18:09.760 に答える
-1

It seems that using getSVGDocument() was the key here. I set mouse events a little differently, so ignore that part, but i'm sure others can figure out how to implement the examples into their own stuff.

sb.addEvent(datePickerBtn, 'mouseover', function() {
    var path = this.getElementsByTagName('object')[0].getSVGDocument().getElementById('icon');
    path.style.setProperty('fill', '#ffffff');
});

sb.addEvent(datePickerBtn.getElementsByTagName('object')[0].getSVGDocument(), 'mousedown', datePickerBtnClick);

The code above sets the fill to white onmouseover and fires a function when clicked. Keep in mind you have to name your svg elements and its easiest to do this stuff when your svg contains only a single named element, otherwise you'd have to repeat this process for each separate element in the svg.

Another note to pay attention to is that for some reason (at least in firefox, possibly others but I have only tested in FF) the click event is not registered with svg, use mousedown instead.

于 2013-02-10T17:48:05.173 に答える