原生js配合cookie制作保存路径的拖拽

主要是运用了原生js封装了一个cookie,然后使用了三个事件做拖拽,分别是onmousedown,onmousemove,onmouseup,这三个事件其中两个需要添加事件对象,也就是event,事件对象是一个不兼容的东西,所以需要处理兼容性的问题,也就是oEvent = ev || event; 通过事件对象,获取鼠标点击屏幕时的那个点,然后减去被拖拽物体距离左边的一个距离,最终就可以获取到当前点击位置距离物体的距离。

最后在onmouseup的时候做了一个return false,主要是为了阻止在高版本浏览器下选中文字。通过cookie里面的addCookie方法,把物体拖动停止时的位置存在了cookie里面,然后在页面加载的时候就调用getCookie方法,取到物体所在的位置,也就做了一个用cookie存位置的拖拽。

如有下边的html:

<div>拖动我</div>

CSS:

#drag{width: 100px; height: 100px; background: red; position: absolute; top: 0; left: 0;cursor:move;}

使用用js实现拖动的代码如下:

function addCookie(name, value, iDay) { var oDate = new Date(); oDate.setDate(oDate.getDate() + iDay); document.cookie = name + '=' + value + '; path=https://www.jb51.net/; 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; }; } };

以上就是原生js配合cookie制作保存路径的拖拽实现效果,希望对大家的学习有所启发。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwxxx.html