layui js 图片碰撞替换位置

本文介绍了一个使用JavaScript实现的动态图片列表,支持图片编辑和删除,以及通过拖拽调整元素顺序。通过API与服务器交互,实时更新菜单结构,适合前端开发人员了解和学习前端交互设计和后端接口调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@using System.Data;
@model object[]
@{
    Layout = "~/Views/Shared/_DisplayLayout.cshtml";
    string type = Model[0] as string;
}
<script type="text/javascript">
    //加载时查询默认的当前的id顺序
    var loadval = [];
</script>
<div class="layui-col-md12">
    <div class="layui-card layui-form" id="content">
        <div class="layui-col-md12">
            <div class="layui-card layui-form" id="content">
                <ul id="ul1">
                    @*<li><img src="~/img/1.jpg" width="200" height="150" /></li>
                        <li><img src="~/img/2.jpg" width="200" height="150" /></li>
                        <li><img src="~/img/3.jpg" width="200" height="150" /></li>
                        <li><img src="~/img/4.jpg" width="200" height="150" /></li>
                        <li><img src="~/img/5.jpg" width="200" height="150" /></li>
                        <li><img src="~/img/6.jpg" width="200" height="150" /></li>*@
                </ul>
                <span style="clear:none"></span>
            </div>
        </div>
    </div>
</div>
<style type="text/css">
    .span {
        width: 170px;
        height: 160px;
    }

    .img {
        width: 150px;
        height: 150px;
    }

    #ul1 {
        width: 100%;
        position: relative;
        margin: 10px auto;
        /*height: 200px*/
    }

        #ul1 li {
            width: 200px;
            height: 150px;
            float: left;
            margin: 25px;
            -moz-border-radius: 3px;
            border-radius: 3px;
            text-align: center;
        }

            #ul1 li:hover {
                border-color: #9a9fa4;
                box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.85);
            }

        #ul1 .active {
            border: 1px dashed red;
        }

        #ul1 li img {
            -moz-border-radius: 3px;
            border-radius: 3px;
            width: auto;
            height: auto;
            max-width: 100%;
            max-height: 100%;
        }

    .sp {
        text-align: center;
        height: 35px;
        font-size: 16px;
        /*line-height: 35px;*/
    }

    .gddw {
        background-color: #5BB9FF;
        height: 35px;
        width: 100%;
        position: absolute;
        bottom: 0px;
        /*left: 6.5px;*/
        /*padding: 0px 10px;*/
        border-radius: 3px;
    }
</style>
<script type="text/javascript">
    //修改
    function edit(id, type) {
        console.log(id, type);
        //在iframe子页面中查找父页面元素
        //alert($('#content', window.parent.document).html());
        parent.edit(id, type);
    }
    //删除
    function del(id) {
        layer.confirm("确认要删除吗,删除后不能恢复", { title: "删除确认" }, function (index) {
            var data = {
                "clientid": clientid,
                "timestamp":Date.parse(new Date()),
                "token": token,
                "smid": smid,
                "href": href,
                "cmd": "delguide",
                "menuid": id
            };
            var md5 = ByParGetMd5(data);
            var se = function () {
                location.reload();
            }
            if (md5 != "") {
                $.ajax({
                    type: "post",
                    data: $.extend(data, {
                        "sign": md5,
                    }),
                    url: url,
                    dataType: "json",
                    cache: true,
                    async: true,
                    success: function (text) {
                        ReturnLoginPage(text.status);
                        if (text.status == 1) {
                            $.tbmAlertWarning(text.msg);
                        }
                        else {
                            $.tbmAlertSuccess(text.msg, se);
                        }
                    }
                });
            }
        });
    }
     $(function () {
        var data = $.extend(data, {
            "clientid": clientid,
            "timestamp":Date.parse(new Date()),
            "token": token,
            "smid": smid,
            "href": href,
            "cmd": "findguidemenu",
            "types": "@type"
        });
        var md5 = ByParGetMd5(data);
        if (md5 != "") {
            $.ajax({
                type: "post",
                data: $.extend(data, {
                    "sign": md5,
                }),
                url: url,
                dataType: "json",
                cache: false,
                async: false,
                success: function (text) {
                    ReturnLoginPage(text.status);
                    console.log(text);
                    var lis = "";
                    if ("@type"=="1"||"@type"=="2"||"@type"=="6"||"@type"=="9") {
                        if (text.success == true) {
                            for (var i = 0; i < text.response.length; i++) {
                                lis += "<li data-id=" + text.response[i]["id"] + "><img src=\"" + text.response[i]["guide_pic"] + "\" width=\"200\" height=\"150\" />";
                                lis += "<div class='gddw'><div style=\"float:right;line-height:35px;color:black;padding-right:30px;\"><i class=\"layui-icon\" style=\"font-size:25px;cursor:pointer;\" onclick=\"edit(" + text.response[i]["id"] + "," + text.response[i]["types"]+")\">&#xe642;";
                                lis += "</i><i class=\"layui-icon\" style=\"font-size: 25px;cursor:pointer;\" onclick=\"del(" + text.response[i]["id"] + ")\">&#xe640;</i></div></div></li>";
                            }
                        }
                    }
                    else {
                        if (text.success == true) {
                            for (var i = 0; i < text.response.length; i++) {
                                lis += "<li data-id=" + text.response[i]["id"] + "><img src=\"" + text.response[i]["guide_pic"] + "\" width=\"200\" height=\"150\" />";
                                lis += "<div class='gddw'><div style=\"float:right;line-height:35px;color:black;padding-right:30px;\"><i class=\"layui-icon\" style=\"font-size:25px;cursor:pointer;\" onclick=\"edit(" + text.response[i]["id"] + "," + text.response[i]["types"] + ")\">&#xe642;";
                                lis += "</i><i class=\"layui-icon\" style=\"font-size: 25px;cursor:pointer;\" onclick=\"del(" + text.response[i]["id"] +")\">&#xe640;</i></div></div>";
                                lis += "<div class='sp'>" + text.response[i]["names"] +"</div></li > ";
                            }
                        }
                    }
                    $("#ul1").append(lis);
                }
            });
         }

    var oUl = document.getElementById("ul1");
    var aLi = oUl.getElementsByTagName("li");
    var disX = 0;
    var disY = 0;
    var minZindex = 1;
         var aPos = [];
    for (var i = 0; i < aLi.length; i++) {
        var t = aLi[i].offsetTop;
        var l = aLi[i].offsetLeft;
        aLi[i].style.top = t + "px";
        aLi[i].style.left = l + "px";
        aPos[i] = { left: l, top: t };
        aLi[i].index = i;
        var row = {};
        row.id = aLi[i].getAttribute("data-id");
        loadval.push(row);
    }
    for (var i = 0; i < aLi.length; i++) {
        aLi[i].style.position = "absolute";
        aLi[i].style.margin = 0;
        setDrag(aLi[i]);
         }
         console.log(loadval);
    //拖拽
    function setDrag(obj) {
        obj.onmouseover = function () {
            obj.style.cursor = "move";
        }
        obj.onmousedown = function (event) {
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
            obj.style.zIndex = minZindex++;
            //当鼠标按下时计算鼠标与拖拽对象的距离
            disX = event.clientX + scrollLeft - obj.offsetLeft;
            disY = event.clientY + scrollTop - obj.offsetTop;
            document.onmousemove = function (event) {
                //当鼠标拖动时计算div的位置
                var l = event.clientX - disX + scrollLeft;
                var t = event.clientY - disY + scrollTop;
                obj.style.left = l + "px";
                obj.style.top = t + "px";
                /*for(var i=0;i<aLi.length;i++){
                    aLi[i].className = "";
                    if(obj==aLi[i])continue;//如果是自己则跳过自己不加红色虚线
                    if(colTest(obj,aLi[i])){
                        aLi[i].className = "active";
                    }
                }*/
                for (var i = 0; i < aLi.length; i++) {
                    aLi[i].className = "";
                }
                var oNear = findMin(obj);
                if (oNear) {
                    oNear.className = "active";
                }
            }
            document.onmouseup = function () {
                document.onmousemove = null;//当鼠标弹起时移出移动事件
                document.onmouseup = null;//移出up事件,清空内存
                //检测是否普碰上,在交换位置
                var oNear = findMin(obj);
                var oNear_id = oNear.getAttribute("data-id");
                var obj_id = obj.getAttribute("data-id");
                if (oNear) {
                    oNear.className = "";
                    //替换data-id的值然后从新排序
                    oNear.attributes[0].value = obj_id;
                    obj.attributes[0].value = oNear_id;
                    oNear.style.zIndex = minZindex++;
                    obj.style.zIndex = minZindex++;
                    startMove(oNear, aPos[obj.index]);
                    startMove(obj, aPos[oNear.index]);
                  //交换index
                    oNear.index += obj.index;
                    obj.index = oNear.index - obj.index;
                    oNear.index = oNear.index - obj.index;
                } else {
                    startMove(obj, aPos[obj.index]);
                }
            }
            clearInterval(obj.timer);
            return false;//低版本出现禁止符号
        }
    }
 //碰撞检测
    function colTest(obj1, obj2) {
        var t1 = obj1.offsetTop;
        var r1 = obj1.offsetWidth + obj1.offsetLeft;
        var b1 = obj1.offsetHeight + obj1.offsetTop;
        var l1 = obj1.offsetLeft;

        var t2 = obj2.offsetTop;
        var r2 = obj2.offsetWidth + obj2.offsetLeft;
        var b2 = obj2.offsetHeight + obj2.offsetTop;
        var l2 = obj2.offsetLeft;

        if (t1 > b2 || r1 < l2 || b1 < t2 || l1 > r2) {
            return false;
        } else {
            return true;
        }
    }
 //勾股定理求距离
    function getDis(obj1, obj2) {
        var a = obj1.offsetLeft - obj2.offsetLeft;
        var b = obj1.offsetTop - obj2.offsetTop;
        return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
    }
//找到距离最近的
    function findMin(obj) {
        var minDis = 999999999;
        var minIndex = -1;
        for (var i = 0; i < aLi.length; i++) {
            if (obj == aLi[i]) continue;
            if (colTest(obj, aLi[i])) {
                var dis = getDis(obj, aLi[i]);
                if (dis < minDis) {
                    minDis = dis;
                    minIndex = i;
                }
            }
        }
        if (minIndex == -1) {
            return null;
        } else {
            return aLi[minIndex];
        }
    }
    });

</script>
<script src="../js/move.js"></script>

move.js


//通过class获取元素
function getClass(cls) {
    var ret = [];
    var els = document.getElementsByTagName("*");
    for (var i = 0; i < els.length; i++) {
        //判断els[i]中是否存在cls这个className;.indexOf("cls")判断cls存在的下标,如果下标>=0则存在;
        if (els[i].className === cls || els[i].className.indexOf("cls") >= 0 || els[i].className.indexOf(" cls") >= 0 || els[i].className.indexOf(" cls ") > 0) {
            ret.push(els[i]);
        }
    }
    return ret;
}
function getStyle(obj, attr) {//解决JS兼容问题获取正确的属性值
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];
}
var map = new Map();
function startMove(obj, json, fun) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function () {
        var isStop = true;
        for (var attr in json) {
            var iCur = 0;
            //判断运动的是不是透明度值
            if (attr == "opacity") {
                iCur = parseInt(parseFloat(getStyle(obj, attr)) * 100);
            } else {
                iCur = parseInt(getStyle(obj, attr));
            }
            var ispeed = (json[attr] - iCur) / 8;
            //运动速度如果大于0则向下取整,如果小于0想上取整;
            ispeed = ispeed > 0 ? Math.ceil(ispeed) : Math.floor(ispeed);
            //判断所有运动是否全部完成
            if (iCur != json[attr]) {
                isStop = false;
            }
            //运动开始
            if (attr == "opacity") {
                obj.style.filter = "alpha:(opacity:" + (json[attr] + ispeed) + ")";
                obj.style.opacity = (json[attr] + ispeed) / 100;
            } else {
                obj.style[attr] = iCur + ispeed + "px";
            }
        }

        //判断是否全部完成
        if (isStop) {
            clearInterval(obj.timer);
            if (fun) {
                fun();
            }
            console.log(isStop);
            if (isStop) {
                var oUl = document.getElementById("ul1");
                var aLi = oUl.getElementsByTagName("li");
                console.log(aLi);
                for (var s = 0; s < aLi.length; s++) {
                    var l = aLi[s].offsetLeft;
                    //map.set(aLi[s].getAttribute("data-id"), l);
                    if (l == 25) {
                        var menuids = [];
                        // var arrayObj = Array.from(map);
                       // console.log(arrayObj);
                        // arrayObj.sort(function (a, b) { return a[1] - b[1] });
                        //for (var i = 0; i < arrayObj.sort(function (a, b) { return a[1] - b[1] }).length; i++) {
                        //    var row = {};
                        //    row.id = arrayObj.sort(function (a, b) { return a[1] - b[1] })[i][0];
                        //    menuids.push(row);
                        //}
                        for (var i = 0; i < aLi.length; i++) {
                            var row = {};
                            row.id = aLi[i].getAttribute("data-id");
                            menuids.push(row);
                        }
                        console.log(menuids);
                        var data = $.extend(data, {
                            "clientid": clientid,
                            "cmd": "changeguidelistordercode",
                            "href": href,
                            "token": token,//token
                            "timestamp": Date.parse(new Date()),
                            "menuids": JSON.stringify(menuids),
                            "smid": smid
                        });
                        var md5 = ByParGetMd5(data);
                        var se = function () {
                            location.reload();
                            //closethis();
                        }
                        console.log(loadval, menuids, loadval.length, menuids.length, JSON.stringify(loadval), JSON.stringify(menuids));
                        if (md5 != "" && JSON.stringify(loadval) != JSON.stringify(menuids) && loadval.length == menuids.length) {//
                            $.ajax({
                                type: "post",
                                data: $.extend(data, {
                                    "sign": md5,
                                }),
                                url: url,
                                dataType: "json",
                                cache: true,
                                async: true,
                                success: function (text) {
                                    if (text.status == 1) {
                                        $.tbmAlertWarning(text.msg);
                                    }
                                    else {
                                        $.tbmAlertSuccess(text.msg, se);
                                    }
                                }
                            });
                        }
                    }
                }
            }
        }
    }, 30);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值