Clickable link on a SVG circle, text or line

你说的曾经没有我的故事 提交于 2019-12-12 01:43:15

问题


Using snapsvg.io, I would like to know if it's possible to add a clickable link such as a <a href="somelink.com"/>My Link</a> tag to an SVG text, circle or line.

An example here I have is text:

var s = Snap("#svg");
var text = s.text(x + 10, y - 5, 'My Text');
text.attr({
        fill: doesExist ? alert : textColorOK,
        fontSize: '10px',
        'font-weight': '600',
        'font-family': 'Arial Narrow, sans-serif',
        'text-anchor': 'start',
        cursor: doesExist ? 'pointer' : 'default'
      });

I'd like to do this with snapsvg.io. Furthermore, I want to do this in plain JavaScript, not jQuery.


回答1:


There is an SVG <a> element.

I don't know Snap, and from my fast testings, I wasn't able to set the xlink:href directly from the library, but here is a workaround :

var s = Snap("#mySVG1");

var a = s.el('a');

a.node.setAttributeNS('http://www.w3.org/1999/xlink', 'href', 'http://stackoverflow.com');

a.add(s.text(0, 100, "I'm a link"))
<script src="http://cdn.jsdelivr.net/snap.svg/0.1.0/snap.svg-min.js"></script>
<svg id="mySVG1" height="200" width="200" viewBox="0 0 200 200">
</svg>



回答2:


Kaiido's answer is correct (so I am using that, so don't accept this as the answer), but just to extend that answer if it helps, you can add a plugin to do it, in case you need to do this a lot, so it could look like this...

Snap.plugin( function( Snap, Element, Paper, global ) {
    Element.prototype.a = function( link, element ) {
        var a = s.el('a');
        a.node.setAttributeNS('http://www.w3.org/1999/xlink', 'href', link);
        return a.add( element )
    };
});

var c = s.circle(20,20,20);
var t = s.text(0,100,'Hi there, click me')
s.a( 'http://www.stackoverflow.com', c).attr({ stroke: 'red', fill: 'red'})
s.a( 'http://www.stackoverflow.com', t).attr({ stroke: 'red', fill: 'red'})



回答3:


Appreciate the responses but ended up using a click event, say to a text element i.e.

text.click(function () {
    window.location.href = "http://stackoverflow.com/";
});


来源:https://stackoverflow.com/questions/37592540/clickable-link-on-a-svg-circle-text-or-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!