拉菲尔JS拖放

20

我正在使用raphaeljs开发我的Web应用程序。 我想要设置对象的可放置边界。对象可以在可放置区域内移动。一旦对象进入可放置区域,该对象就不应该有任何离开可放置区域的方法。

1个回答

63
Raphael内置了拖放支持,通过使用 .drag() 实现。可以使用形式为 element.drag(start, move, up); 的方式进行操作,其中三个参数是你编写的处理鼠标按下、移动和弹起事件的函数的引用。
请注意,this.oxthis.oy 用于存储起始位置,dxdy 用于移动。 以下示例实现了一个拖放的盒子。该盒子可以随时移动,但一旦进入“监狱”区域,就不能再移动回来。当盒子进入“监狱”时,颜色会立即改变,向用户发出功能已更改的信号。
在将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)实现此功能。

jsFiddle示例

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);
};​

如果我尝试将元素更改为除矩形以外的任何其他形状,例如圆形(使用R.circle(200,200,40)...)或椭圆形,我就无法再移动它了。还有其他人遇到同样的问题吗?看起来拖动(drag())方法不应该只适用于矩形。 - mags

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接