拖动图片,改变位置

CSS

复制代码
.box_div{
        height: 100px;
    }
    .img-div img {
        width:100px;
        height:100px;
        float: left;
    }
    .img-div {
        float: left;
    }
    .drop-left,.drop-right {
        width: 50px;
        height: 100px;
        float: left;
    }
复制代码

HTML

复制代码
<div class="box_div">
        <div class="img-div">
            <div class="drop-left"></div>
            <img src="http://photos.tuchong.com/38538/f/6864556.jpg" draggable="true">
            <div class="drop-right"></div>
        </div>
        <div class="img-div">
            <img src="http://photos.tuchong.com/349669/f/6695960.jpg" draggable="true">
            <div class="drop-right"></div>
        </div>
        <div class="img-div">
            <img src="http://photos.tuchong.com/349669/f/6683901.jpg" draggable="true">
            <div class="drop-right"></div>
        </div>
        <div class="img-div">
            <img src="http://photos.tuchong.com/349669/f/5121337.jpg" draggable="true">
            <div class="drop-right"></div>
        </div>
    </div>
    <br>
    <div class="box_div">
        <div class="img-div">
            <div class="drop-left"></div>
            <img src="http://photos.tuchong.com/38538/f/6864556.jpg" draggable="true">
            <div class="drop-right"></div>
        </div>
        <div class="img-div">
            <img src="http://photos.tuchong.com/349669/f/6695960.jpg" draggable="true">
            <div class="drop-right"></div>
        </div>
        <div class="img-div">
            <img src="http://photos.tuchong.com/349669/f/6683901.jpg" draggable="true">
            <div class="drop-right"></div>
        </div>
        <div class="img-div">
            <img src="http://photos.tuchong.com/349669/f/5121337.jpg" draggable="true">
            <div class="drop-right"></div>
        </div>
    </div>
复制代码

JS

复制代码
 // drop-right是为了拖动到所以图片的右边设置的。drop-left是为了拖动到第一个图片的左边设置的
    $(document).ready(function() {
        // 正在拖动的图片的父级DIV
        var $srcImgDiv = null;
 
        // 1.开始拖动
        $(".img-div img").bind("dragstart", function() {
            $srcImgDiv = $(this).parent();
        });
 
        // 2.拖动到.drop-left,.drop-right上方时触发的事件
            // $(".drop-left,.drop-right")是给不同元素绑定同一个事件的缩写,即 $(".drop-left")和 $(".drop-right")的缩写
        $(".drop-right,.drop-left").bind("dragover", function(event) {
            // 必须通过event.preventDefault()来设置允许拖放
            event.preventDefault();
        });

        // 3.结束拖动放开鼠标的事件
        $(".drop-right,.drop-left").bind("drop", function(event) {
            event.preventDefault();
            if($srcImgDiv[0] != $(this).parent()[0]) {
                //4.把拖动的元素$srcImgDiv追加拖到结束位置的后面
                $(this).after($srcImgDiv);
            };
        });
    });
复制代码

 

 效果图:

 

posted @   芬-mi  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示