This article mainly introduces the drag-and-drop effect of native js and cookie creation and storage path. For more information, see the article. It mainly uses native js to encapsulate a cookie, three events are used for drag and drop, respectively
Onmousedown, onmousemove, onmouseup,Two of the three events need to add the event object, that is, event. The event object is incompatible, so you need to handle compatibility issues, that is, oEvent = ev | event; the event object is used to obtain the point when the mouse clicks the screen, and the distance between the dragged object and the object to the left is subtracted.
Finally, a return false is made during onmouseup to prevent Text Selection in a high-version browser. By using the addCookie method in the cookie, the position of the object to be dragged to stop exists in the cookie. Then, when the page is loaded, the getCookie method is called to obtain the location of the object, in this case, a drag-and-drop operation is performed on the cookie storage location.
See the following html:
Drag me
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 with cookie to create and save the path. I hope it will be helpful for your learning.