1. 程式人生 > >js 圖片拖拽效果實現

js 圖片拖拽效果實現

1、前端html排列

<div class="row" id="listing_extra_images" name="TophatterList[extra_images]">
            <div class="image_item_content" style="height:80px;margin:10px 0px;">
                <a class="button" mask="true" style="float:left;width:100px;" href="/products/tophatter/imagelookup/id/2/sku/JM10693/element/extra_images/type/figure?_=1544672274714" target="dialog" width="600" height="600"><span>新增副圖</span></a>
                <ul>
                <li>
	                <div class="drag_image_item"><img src="/upload/image/assistant/JM10693/200882812418965_2.jpg">
	                <input type="hidden" name="TophatterList[extra_images][]" value="/upload/image/assistant/JM10693/200882812418965_2.jpg">
	                </div>
                </li>
                <li>
	                <div class="drag_image_item"><img src="/upload/image/assistant/JM10693/c89de4fadcf34dd58bbe789d00a58824.jpg"><input type="hidden" name="TophatterList[extra_images][]" value="/upload/image/assistant/JM10693/c89de4fadcf34dd58bbe789d00a58824.jpg"></div>
	                </li>
                <li>
                <div class="drag_image_item"><img src="/upload/image/assistant/JM10693/495146dbc52feebf518e3da191443ffc.jpg"><input type="hidden" name="TophatterList[extra_images][]" value="/upload/image/assistant/JM10693/495146dbc52feebf518e3da191443ffc.jpg"></div></li>
                <li><div class="drag_image_item"><img src="/upload/image/assistant/JM10693/8269be6b9f5a7c33b020a34f1e2a4d40.jpg"><input type="hidden" name="TophatterList[extra_images][]" value="/upload/image/assistant/JM10693/8269be6b9f5a7c33b020a34f1e2a4d40.jpg"></div>
                </li>
                </ul>            
                </div>
        </div>

2、css設定

#listing_extra_images img{cursor: pointer;}
    .image_item_content{position: relative;}
    .image_item_content li{float: left;margin-right: 10px;width: 80px;height: 80px;}    #這裡需設定寬高

3、js

function Pointer(x, y) {
        this.x = x ;
        this.y = y ;
    }
function Position(left, top) {
    this.left = left ;
    this.top = top ;
}

function imageDragSort(obj) {

        obj.find(".image_item_content .drag_image_item").each(function (i) {

            if($(this).parent()[0].tagName.toLowerCase() != 'li')
            {
                return true;
            }
            var inputName = $(this).parents('.row').attr('name');
            this.init = function () { // 初始化

                this.box = $(this).parent();

                console.log(this.box);
                console.log(this.box.width());
                console.log(this.box.offset().left);
                console.log($(this).parents('.row').offset().left);

                $(this).attr("index", i).css({
                    position: "absolute",
                    left: this.box.offset().left - $(this).parents('.row').offset().left,
                    top: this.box.offset().top - $(this).parents('.row').offset().top
                }).appendTo($(this).parents(".image_item_content"));

                $(this).find(':hidden').attr('name', inputName + '[' + i + ']');
                this.drag();
                obj.attr('hasDrag','yes');
            },
                this.move = function (callback) {  // 移動
                    $(this).stop(true).animate({
                        left: this.box.offset().left - $(this).parents('.row').offset().left,
                        top: this.box.offset().top - $(this).parents('.row').offset().top
                    }, 500, function () {
                        if (callback) {
                            callback.call(this);
                        }
                    });
                },
                this.collisionCheck = function () {
                    var currentItem = this;
                    var direction = null;
                    $(this).siblings(".drag_image_item").each(function () {
                        if (
                            currentItem.pointer.x > this.box.offset().left &&
                            currentItem.pointer.y > this.box.offset().top &&
                            (currentItem.pointer.x < this.box.offset().left + this.box.width()) &&
                            (currentItem.pointer.y < this.box.offset().top + this.box.height())
                        ) {
                            // 返回物件和方向
                            if (currentItem.box.offset().top < this.box.offset().top) {
                                direction = "down";
                            } else if (currentItem.box.offset().top > this.box.offset().top) {
                                direction = "up";
                            } else {
                                direction = "normal";
                            }
                            this.swap(currentItem, direction);
                        }
                    });
                },
                this.swap = function (currentItem, direction) { // 交換位置
                    if (this.moveing) return false;
                    var directions = {
                        normal: function () {
                            var saveBox = this.box;
                            this.box = currentItem.box;
                            currentItem.box = saveBox;
                            this.move();
                            $(this).attr("index", this.box.index());
                            $(this).find(':hidden').attr('name', inputName + '[' + this.box.index() + ']');
                            $(currentItem).attr("index", currentItem.box.index()).find(':hidden').attr('name', inputName + '[' + currentItem.box.index() + ']');
                        },
                        down: function () {
                            // 移到上方
                            var box = this.box;
                            var node = this;
                            var startIndex = currentItem.box.index();
                            var endIndex = node.box.index();
                            for (var i = endIndex; i > startIndex; i--) {
                                var prevNode = $(this).parents('.image_item_content').find(".drag_image_item[index=" + (i - 1) + "]")[0];
                                node.box = prevNode.box;
                                $(node).attr("index", node.box.index());
                                $(node).find(':hidden').attr('name', inputName + '[' + node.box.index() + ']');
                                node.move();
                                node = prevNode;
                            }
                            currentItem.box = box;
                            $(currentItem).attr("index", box.index()).find(':hidden').attr('name', inputName + '[' + box.index() + ']');
                        },
                        up: function () {
                            // 移到上方
                            var box = this.box;
                            var node = this;
                            var startIndex = node.box.index();
                            var endIndex = currentItem.box.index();
                            for (var i = startIndex; i < endIndex; i++) {
                                var nextNode = $(this).parents('.image_item_content').find(".drag_image_item[index=" + (i + 1) + "]")[0];
                                node.box = nextNode.box;
                                $(node).attr("index", node.box.index());
                                $(node).find(':hidden').attr('name', inputName + '[' + node.box.index() + ']');
                                node.move();
                                node = nextNode;
                            }
                            currentItem.box = box;
                            $(currentItem).attr("index", box.index()).find(':hidden').attr('name', inputName + '[' + box.index() + ']');
                        }
                    }
                    directions[direction].call(this);
                },
                this.drag = function () { // 拖拽
                    var oldPosition = new Position();
                    var oldPointer = new Pointer();
                    var isDrag = false;
                    var currentItem = null;
                    $(this).mousedown(function (e) {
                        e.preventDefault();
                        oldPosition.left = $(this).position().left;
                        oldPosition.top = $(this).position().top;
                        oldPointer.x = e.clientX;
                        oldPointer.y = e.clientY;
                        isDrag = true;

                        currentItem = this;

                    });
                    $(document).mousemove(function (e) {
                        var currentPointer = new Pointer(e.clientX, e.clientY);
                        if (!isDrag) return false;
                        $(currentItem).css({
                            "opacity": "0.8",
                            "z-index": 999
                        });
                        var left = currentPointer.x - oldPointer.x + oldPosition.left;
                        var top = currentPointer.y - oldPointer.y + oldPosition.top;
                        $(currentItem).css({
                            left: left,
                            top: top
                        });
                        currentItem.pointer = currentPointer;
                        // 開始交換位置
                        currentItem.collisionCheck();
                    });
                    $(document).mouseup(function () {
                        if (!isDrag) return false;
                        isDrag = false;
                        currentItem.move(function () {
                            $(this).css({
                                "opacity": "1",
                                "z-index": 0
                            });
                        });
                    });
                }
            this.init();
        });
    }

4、物件呼叫

imageDragSort($('#listing_extra_images'));