我正在使用raphaeljs开发我的Web应用程序。 我想要设置对象的可放置边界。对象可以在可放置区域内移动。一旦对象进入可放置区域,该对象就不应该有任何离开可放置区域的方法。
我正在使用raphaeljs开发我的Web应用程序。 我想要设置对象的可放置边界。对象可以在可放置区域内移动。一旦对象进入可放置区域,该对象就不应该有任何离开可放置区域的方法。
.drag()
实现。可以使用形式为 element.drag(start, move, up);
的方式进行操作,其中三个参数是你编写的处理鼠标按下、移动和弹起事件的函数的引用。this.ox
和 this.oy
用于存储起始位置,dx
和 dy
用于移动。
以下示例实现了一个拖放的盒子。该盒子可以随时移动,但一旦进入“监狱”区域,就不能再移动回来。当盒子进入“监狱”时,颜色会立即改变,向用户发出功能已更改的信号。Math.min()
和Math.max()
调整盒子的位置。var nowX, nowY, move = function (dx, dy) {
// move will be called with dx and dy
if (this.attr("y") > 60 || this.attr("x") > 60)
this.attr({x: this.ox + dx, y: this.oy + dy});
else {
nowX = Math.min(60, this.ox + dx);
nowY = Math.min(60, this.oy + dy);
nowX = Math.max(0, nowX);
nowY = Math.max(0, nowY);
this.attr({x: nowX, y: nowY });
if (this.attr("fill") != "#000") this.attr({fill: "#000"});
}
}
你还可以使得盒子被放入“囚禁”盒子后无法再次拾取。可以在 move()
或 start()
函数中检查位置,或在 stop()
函数中使用c.undrag(f)
实现此功能。
window.onload = function() {
var nowX, nowY, R = Raphael("canvas", 500, 500),
c = R.rect(200, 200, 40, 40).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
cursor: "move"
}),
j = R.rect(0,0,100,100),
// start, move, and up are the drag functions
start = function () {
// storing original coordinates
this.ox = this.attr("x");
this.oy = this.attr("y");
this.attr({opacity: 1});
if (this.attr("y") < 60 && this.attr("x") < 60)
this.attr({fill: "#000"});
},
move = function (dx, dy) {
// move will be called with dx and dy
if (this.attr("y") > 60 || this.attr("x") > 60)
this.attr({x: this.ox + dx, y: this.oy + dy});
else {
nowX = Math.min(60, this.ox + dx);
nowY = Math.min(60, this.oy + dy);
nowX = Math.max(0, nowX);
nowY = Math.max(0, nowY);
this.attr({x: nowX, y: nowY });
if (this.attr("fill") != "#000") this.attr({fill: "#000"});
}
},
up = function () {
// restoring state
this.attr({opacity: .5});
if (this.attr("y") < 60 && this.attr("x") < 60)
this.attr({fill: "#AEAEAE"});
};
// rstart and rmove are the resize functions;
c.drag(move, start, up);
};