使用 Raphael,我希望能够拖动包含文本对象的形状(下例中的椭圆),拖动形状或文本。我希望通过设置传递给文本元素的 drag()
方法的函数来委托(delegate)给关联的形状来实现此目的(尝试对 this other one 采取更具多态性的方法)。但是,当调用 text.drag(...)
时,这会导致错误“obj.addEventListener 不是函数”。
我是 javascript 新手,所以我可能犯了一个非常明显的错误,但我无法发现它。我是否在委托(delegate)函数 moveText
、dragText
和 upText
中误用了 call()
?或者这是拉斐尔的作品?任何帮助将不胜感激。
<html>
<head>
<title>Raphael delegated drag test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="js/raphael.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function initPage() {
'use strict';
var paper = Raphael("holder", 640, 480);
var shape = paper.ellipse(190,100,30, 20).attr({
fill: "green",
stroke: "green",
"fill-opacity": 0,
"stroke-width": 2,
cursor: "move"
});
var text = paper.text(190,100,"Ellipse").attr({
fill: "green",
stroke: "none",
cursor: "move"
});
// Associate the shape and text elements with each other
shape.text = text;
text.shape = shape;
// Drag start
var dragShape = function () {
this.ox = this.attr("cx");
this.oy = this.attr("cy");
}
var dragText = function () {
dragShape.call(this.shape);
}
// Drag move
var moveShape = function (dx, dy) {
this.attr({cx: this.ox + dx, cy: this.oy + dy});
this.text.attr({x: this.ox + dx, y: this.oy + dy});
}
var moveText = function (dx,dy) {
moveShape.call(this.shape,dx,dy);
}
// Drag release
var upShape = function () {
}
var upText = function () {
upShape.call(this.shape);
}
shape.drag(moveShape, dragShape, upShape);
text.drag(moveText, dragText, upText);
};
</script>
<div id="holder"></div>
</body>
</html>
解决方案
正如 this answer 中指出的,问题出现在属性名称的选择上:
// Associate the shape and text elements with each other
shape.text = text;
text.shape = shape;
将这些名称更改为更详细的名称(并且不太可能与 Raphael 发生冲突)可以使问题消失,但将它们设置为 data
更安全。属性:
// Associate the shape and text elements with each other
shape.data("enclosedText",text);
text.data("parentShape",shape);
// Drag start
var dragShape = function () {
this.ox = this.attr("cx");
this.oy = this.attr("cy");
}
var dragText = function () {
dragShape.call(this.data("parentShape"));
}
// Drag move
var moveShape = function (dx, dy) {
this.attr({cx: this.ox + dx, cy: this.oy + dy});
this.data("enclosedText").attr({x: this.ox + dx, y: this.oy + dy});
}
var moveText = function (dx,dy) {
moveShape.call(this.data("parentShape"),dx,dy);
}
最佳答案
// Associate the shape and text elements with each other
shape.text = text;
text.shape = shape;
您正在向 Raphael 对象添加属性。如果不知道拉斐尔如何工作(或将来会如何工作),这是危险的,而且显然也是导致问题的原因。如果您确实想关联它们,我建议使用 Raphaels Element.data
:http://raphaeljs.com/reference.html#Element.data
关于javascript - Raphael 中的委托(delegate)拖动功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830330/