Mainly uses native js to encapsulate a cookie, and then uses three events for drag and drop, namely onmousedown, onmousemove, onmouseup, two of these three events You need to add an event object, that is, event. The event object is an incompatible thing, so you need to deal with compatibility issues, that is, oEvent = ev || event; Through the event object, get the point when the mouse clicks on the screen, and then Subtract a distance from the left side of the dragged object, and finally you can get the distance from the current click position to the object.
Finally, a return false was made during onmouseup, mainly to prevent text from being selected in higher version browsers. Through the addCookie method in the cookie, the position when the object dragging stops is stored in the cookie, and then when the page is loaded, the getCookie method is called to get the position of the object, and a drag and drop that uses a cookie to save the position is made. .
If there is the following html:
<div id="drag">拖动我</div>
CSS:
#drag{width: 100px; height: 100px; background: red; position: absolute; top: 0; left: 0;cursor:move;}
The code for dragging using js is as follows:
function addCookie(name, value, iDay) { var oDate = new Date(); oDate.setDate(oDate.getDate() + iDay); document.cookie = name + '=' + value + '; path=/; expires=' + oDate; } function getCookie(name) { var arr = document.cookie.split('; '); for (var i = 0; i < arr.length; i++) { var arr2 = arr[i].split('='); return (arr2[0] == name) && arr2[1] } return ''; } window.onload = function () { var oDiv = document.getElementById('drag'); drag(oDiv); var move_by = getCookie('move_cood'); if (move_by) { var str = eval('(' + move_by + ')'); oDiv.style.left = str[0] + 'px'; oDiv.style.top = str[1] + 'px'; } function drag(obj) { obj.onmousedown = function (ev) { var oEvent = ev || event; var disX = oEvent.clientX - obj.offsetLeft, disY = oEvent.clientY - obj.offsetTop; document.onmousemove = function (ev) { var oEvent = ev || event; obj.style.left = oEvent.clientX - disX + 'px'; obj.style.top = oEvent.clientY - disY + 'px'; }; document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; obj.releaseCapture && obj.releaseCapture(); addCookie('move_cood', '[' + obj.offsetLeft + ',' + obj.offsetTop + ']', 10); }; obj.setCapture && obj.setCapture(); return false; }; } };
The above is the drag-and-drop effect of native js combined with cookie creation and saving path. I hope it will inspire everyone's learning.