简体   繁体   English

使用SVG.js选择文本元素

[英]Selecting Text element with SVG.js

I'm using the library SVG.js and svg.select.js to manipulate svg objects, I have problems selecting text elements as you can see in this example . 我正在使用库SVG.js和svg.select.js来处理svg对象,在选择文本元素时遇到了问题,如本例所示 With the ellipse there are no problems while this is the error message when trying to select the text: "Uncaught TypeError: this.parent.group is not a function" This is my code: 使用椭圆没有问题,而这是尝试选择文本时的错误消息:“未捕获的TypeError:this.parent.group不是函数”这是我的代码:

var draw = SVG('drawing')
var selectedelement;
var g = draw.group();
text = g.text('Perepepeeeee');
var myEllipse = g.ellipse(50, 50);
myEllipse.move(200, 0);

g.on("click", function (event) {
   if (selectedelement!=null)
      selectedelement.selectize(false, { deepSelect: true });
   selectedelement=SVG.get(event.target.id).selectize({ deepSelect: true })
});

Where am I wrong? 我哪里错了?

You access the event.target.id in your event handler. 您可以在事件处理程序中访问event.target.id The target property always points to the node the event was invoked on. target属性始终指向在其上调用事件的节点。 In your case thats the tspan . 您的情况就是tspan However, what you want is the text. 但是,您想要的是文本。

svg.js calls the handler in the context of the element it was bound on. svg.js在绑定元素的上下文中调用处理程序。 So you can simply use this to get the group and search the text-element from there: 因此,您可以简单地使用this来获取组并从那里搜索文本元素:

g.on("click", function (event) {
   if (selectedelement!=null)
      selectedelement.selectize(false, { deepSelect: true });
   selectedelement = this.select('text').first().selectize({ deepSelect: true })
});

However, the best way would be to bind the click event to the text at the first place so you dont need to traverse through the dom 但是,最好的方法是首先将click事件绑定到文本,因此您无需遍历dom

text.on("click", function (event) {
   if (selectedelement!=null)
      selectedelement.selectize(false, { deepSelect: true });
   selectedelement = this.selectize({ deepSelect: true })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM