日期:2014-05-16  浏览次数:20402 次

關於移動範圍問題,來者都有分!
如圖所示,6條黑邊是由DIV所組成的牆壁,要求圖片不能移出牆壁。
如果複雜點的話 DIV牆壁的位置和數量都是不確定的,但是連起來後是個封閉的容器。

假設牆壁的對象為wallObj,圖片的對象為imgObj。
其他需要的變量可以按照思路自己加。




------解决方案--------------------
图呢?
------解决方案--------------------
我先貼上我的做法,是個回調函數
JScript code
rangeMoveFunc : function(obj,e,x,y){//obj為圖片對象,x為圖片所移動的位置,也就是x = e.pageX//當前移動座標 - (downX//mousedown時的e.pageX; - obj.offset().left)
    var thisWidth = obj.width();
    var thisHeight = obj.height();
    var rx,ry;//圖片所能移動的座標,當rx,ry為undefined時, rx = x;ry = y;
    var left,top,right,bottom;//牆壁的位置
    wallObj.each(function(){
        var offset = $(this).offset();
        switch($(this).attr('pos'))//我定義了牆壁的方向,按牆壁的方向來判斷圖片所移動的位置
        {
            case 'left' : 
                left = offset.left + $(this).width();
                top = offset.top - thisHeight;
                bottom = offset.top + $(this).height();
                if(!rx && x < left && y > top && y < bottom){
                    rx = left;
                }
            break;
            case 'top' : 
                top = offset.top + $(this).height();
                left = offset.left - thisWidth;
                right = offset.left + $(this).width();
                if(!ry && y < top && x > left && x < right){
                    ry = top;
                }
            break;
            case 'right' : 
                right = offset.left - thisWidth;
                top = offset.top - thisHeight;
                bottom = offset.top + $(this).height();
                if(!rx && x > right && y > top && y < bottom){
                    rx = right;
                }
            break;
            case 'bottom' : 
                bottom = offset.top - thisHeight;
                left = offset.left - thisWidth;
                right = offset.left + $(this).width();
                if(!ry && y > bottom && x > left && x < right){
                    ry = bottom;
                }
            break;
        }
        if(rx && ry){
            return false;
        }
    })
    
    return [rx,ry];
}

------解决方案--------------------
总能获得6个div的四个顶点的坐标吧 用坐标判断试试可以不
------解决方案--------------------
单个div的范围是很好判断的。。if(你鼠标的点(如果你拖的时候鼠标是在左上或者中心你还要计算宽度。)超出了。){就不让你的div过去。}在你的mousemove的时候你是可以获取不断变化的坐标的。。然后循环判断是否在某一个div的范围。在要出的时候写个判断 判断你当前所在div和你要出的方向,方向的判断你可以继续上一个坐标值,然后把方向判断出来了就判断对应方向的那条div的边继续往后走是否仍然是某个div的内部 如果是的话就允许移动。如果判断出对应方向那条边继续往后走已经不是某一个div了 就判断此边为墙壁。禁止继续增/减 top或left。。