Native JS to achieve drag photo wall

Native JS to achieve drag photo wall

This article shares with you a draggable photo wall implemented with native JS. The effect is as follows:

The implementation code is as follows:

<!DOCTYPE html>
<html>
 
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Native JS to drag the photo wall and swap photos</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        #ul1 {
            width: 660px;
            position: relative;
            margin: 10px auto;
        }
 
        #ul1 li {
            width: 200px;
            height: 150px;
            float: left;
            list-style: none;
            margin: 10px;
            z-index: 1;
        }
 
        #ul1 .active {
            border: 1px dashed red;
        }
    </style>
    <script src="js/move.js"></script>
    <script>
        window.onload = function () {
 
            var oUl = document.getElementById('ul1');
            var aLi = oUl.getElementsByTagName('li');
            var aPos = [];
            var iMinZindex = 2;
            var i = 0;
 
            //Layout conversion //Get the position of the current layout image for (i = 0; i < aLi.length; i++) {
 
                aPos[i] = { left: aLi[i].offsetLeft, top: aLi[i].offsetTop };
            }
            //Layout conversion requires two for loops to complete for (i = 0; i < aLi.length; i++) {
                //Assign values ​​to each image position aLi[i].style.left = aPos[i].left + 'px';
                aLi[i].style.top = aPos[i].top + 'px';
 
                //Conversion positioning aLi[i].style.position = 'absolute';
                //The value of offset already includes the value of margin, so we need to cancel aLi[i].style.margin = '0';
 
                aLi[i].index = i;
            }
 
            //Loop drag for (i = 0; i < aLi.length; i++) {
                setDrag(aLi[i]);
            }
            function setDrag(obj) {
                //When the mouse is pressed obj.onmousedown = function (ev) {
                    //Event compatible var oEvent = ev || event;
 
                    //Increase the stacking order of the current image obj.style.zIndex = iMinZindex++;
                    //Calculate the mouse position relative to the upper left corner of the dragged object var disX = oEvent.clientX - obj.offsetLeft;
                    var disY = oEvent.clientY - obj.offsetTop;
 
                    //When the mouse moves document.onmousemove = function (ev) {
                        //Event compatible var oEvent = ev || event;
 
                        //Reassign the image position obj.style.left = oEvent.clientX - disX + 'px';
                        obj.style.top = oEvent.clientY - disY + 'px';
 
                        // Clear all li styles for (i = 0; i < aLi.length; i++) {
                            aLi[i].className = '';
                        }
 
                        //Get the nearest target object of the current drag object var oNear = findNearest(obj);
                        //If exists if (oNear) {
                            //Assign the object's class to active
                            oNear.className = 'active';
 
                        }
 
                    };
 
                    //When the mouse is released document.onmouseup = function () {
 
                        document.onmousemove = null;
                        document.onmouseup = null;
 
                        //Get the nearest target object of the current drag object var oNear = findNearest(obj);
 
                        //If there is a nearest collision object if (oNear) {
 
                            oNear.className = '';
 
                            //Add the zIndex of the nearest target object //to prevent movement from the back oNear.style.zIndex = iMinZindex++;
 
                            //When the current drag object moves over the target object, it is located above the target object obj.style.zIndex = iMinZindex++;
 
                            //Move the nearest target object (oNear) to the current object (obj) position startMove(oNear, aPos[obj.index]);
 
                            //Move the current object (obj) to the position of the nearest target object (oNear) startMove(obj, aPos[oNear.index]);
 
 
                            //Exchange the index value of the current drag object and the target object var tmp = 0;
 
                            tmp = obj.index;
                            obj.index = oNear.index;
                            oNear.index = tmp;
 
                            //If there is no nearest collision object} else {
                            //Back to the original position startMove(obj, aPos[obj.index]);
                        }
                    };
 
                    //Clear timer //To prevent jitter when the image is dragged again during the shift process clearInterval(obj.timer);
 
                    //Prevent browser bug, mouse pointer deformation when dragging return false;
                };
            }
 
            //Collision detection function cdTest(obj1, obj2) {
 
                //The left, right, top and bottom contour positions of target 1 var l1 = obj1.offsetLeft;
                var r1 = obj1.offsetLeft + obj1.offsetWidth;
                var t1 = obj1.offsetTop;
                var b1 = obj1.offsetTop + obj1.offsetHeight;
 
                //The left, right, top and bottom contour positions of target 2 var l2 = obj2.offsetLeft;
                var r2 = obj2.offsetLeft + obj2.offsetWidth;
                var t2 = obj2.offsetTop;
                var b2 = obj2.offsetTop + obj2.offsetHeight;
 
                //Compare the outer contours of the two targets to detect whether they collide if (r1 < l2 || l1 > r2 || b1 < t2 || t1 > b2) {
 
                    return false;
 
                } else {
 
                    return true;
                }
            }
 
            //Calculate the distance between the dragged object and other objects function getDis(obj1, obj2) {
 
                var a = obj1.offsetLeft - obj2.offsetLeft;
                var b = obj1.offsetTop - obj2.offsetTop;
 
                return Math.sqrt(a * a + b * b);
            }
 
            //Find the nearest function findNearest(obj) {
 
                //Reference value for finding the minimum value var iMin = 999999999;
 
                var iMinIndex = -1;
 
                for (i = 0; i < aLi.length; i++) {
 
                    //Avoid collision with itself, skip detection if (obj == aLi[i]) {
                        continue
                    };
 
                    //If a collision object is found if (cdTest(obj, aLi[i])) {
                        //Calculate the distance between the dragged object and each li var dis = getDis(obj, aLi[i]);
                        //If the current reference distance is greater than the distance between a certain li and the current drag objectif (iMin > dis) {
                            //Re-assign reference distance (compare multiple times to get the minimum value)
                            iMin = dis;
                            //Get the index of the nearest target iMinIndex = i;
                        }
                    }
                }
 
                //iMinIndex is -1, which means it has never been encountered if (iMinIndex == -1) {
 
                    return null;
 
                    //otherwise} else {
 
                    //Return the li that collided most closely
                    return aLi[iMinIndex];
                }
            }
        };
    </script>
</head>
 
<body>
    <ul id="ul1">
        <li><img src="images/0.jpg" /></li>
        <li><img src="images/1.jpg" /></li>
        <li><img src="images/2.jpg" /></li>
        <li><img src="images/3.jpg" /></li>
        <li><img src="images/4.jpg" /></li>
        <li><img src="images/0.jpg" /></li>
        <li><img src="images/1.jpg" /></li>
        <li><img src="images/2.jpg" /></li>
        <li><img src="images/3.jpg" /></li>
        <li><img src="images/4.jpg" /></li>
    </ul>
</body>
 
</html>

The following is the move.js file introduced in the above code, which is mainly used to achieve motion effects. The code is as follows:

function getStyle(obj, attr) {
    if (obj.currentStyle) {
        return obj.currentStyle[attr];
    } else {
        return getComputedStyle(obj, false)[attr];
    }
}
 
function startMove(obj, json, fn) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function () {
        var bStop = 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;
            iSpeed ​​= iSpeed ​​> 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
 
 
            if (iCur != json[attr]) {
                bStop = false;
            }
 
            if (attr == 'opacity') {
                obj.style.filter = 'alpha(opacity:' + (iCur + iSpeed) + ')';
                obj.style.opacity = (iCur + iSpeed) / 100;
            } else {
                obj.style[attr] = iCur + iSpeed ​​+ 'px';
            }
        }
 
        if (bStop) {
 
            clearInterval(obj.timer);
 
            if (fn) {
                fn();
            }
        }
    }, 30)
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Native js to achieve photo wall effect
  • js to achieve 3D photo wall effect
  • Creating a photo wall with javascript and the problems that arise during the creation process
  • js to achieve a cool photo wall display effect diagram with source code download
  • JavaScript implements the photo wall code by dragging and clicking photos to stick them on top
  • js to achieve photo wall function example
  • Realizing a simple photo wall effect based on three.js

<<:  Web lesson plans, lesson plans for beginners

>>:  Detailed troubleshooting of docker.service startup errors

Recommend

Problems with index and FROM_UNIXTIME in mysql

Zero, Background I received a lot of alerts this ...

A simple and in-depth study of async and await in JavaScript

Table of contents 1. Introduction 2. Detailed exp...

Implementation of WeChat applet message push in Nodejs

Select or create a subscription message template ...

Example of using supervisor to manage nginx+tomcat containers

need: Use docker to start nginx + tomcat dual pro...

Detailed explanation of jQuery chain calls

Table of contents Chain calls A small case Chain ...

Tutorial on installing Apache 2.4.41 on Windows 10

1. Apache 2.4.41 installation and configuration T...

5 commonly used objects in JavaScript

Table of contents 1. JavaScript Objects 1).Array ...

Pure CSS3 realizes the effect of div entering and exiting in order

This article mainly introduces the effect of div ...

jQuery implements Table paging effect

This article shares the specific code of jQuery t...

Analysis of the problem of deploying vue project and configuring proxy in Nginx

1. Install and start nginx # Install nginx sudo a...

Detailed explanation of MySQL batch SQL insert performance optimization

For some systems with large amounts of data, the ...

Object.entries usage you don't know in JavaScript

Table of contents Preface 1. Use for...of to iter...

Sample code on how to implement page caching in vue mobile project

background On mobile devices, caching between pag...