Drag & drop скрипт
Привет. Нашел в интернете простой drag&drop скрипт для свободного перетаскивания блока. Работает и в IE9+, и в Opera 12+.
Можно ли допилить его, чтобы ограничить область перетаскивания родительским элементом? В ссылке выше, например, чтобы окно за <body> не уходило. Подскажите, в каком направлении копать. Или есть какие-либо аналоги подобного на чистом js? var dragging,offsetX,offsetY; var previouslyDragged=Array(); function makeDragable(clickables,dragables){ if (typeof clickables == 'string'){clickables=Array(clickables);} if (typeof dragables == 'string'){dragables=Array(dragables);} for (var i=0; i<clickables.length; i++) { var clickable=document.getElementById(clickables[i]) clickable.setAttribute('onmousedown',"startDrag(event,'"+dragables[i]+"')"); clickable.onmouseup=stopDrag; } } function startDrag(event,elementID) { dragging=document.getElementById(elementID); offsetX=Array();offsetY=Array(); //calculate first drag position: offsetX[0]= event.clientX; //relative mouse within element offsetY[0]= event.clientY; offsetX[1]= -parseInt(dragging.style.left ? dragging.style.left : dragging.offsetLeft); //current position offsetY[1]= -parseInt(dragging.style.top ? dragging.style.top : dragging.offsetTop); if(!previouslyDragged.in_array(dragging)){ //hack: offset margins for first drag only: offsetX[2]= parseInt(window.getComputedStyle(dragging,null).getPropertyValue("margin-left") ? window.getComputedStyle(dragging,null).getPropertyValue("margin-left") : 0); offsetY[2]= parseInt(window.getComputedStyle(dragging,null).getPropertyValue("margin-top") ? window.getComputedStyle(dragging,null).getPropertyValue("margin-top") : 0); } goDrag(event) document.onmousemove=goDrag; } function stopDrag(){ document.onmousemove=null; previouslyDragged.push(dragging); dragging=null; } function goDrag(event){ dragging.style.left=parseInt(event.pageX-offsetX.sum())+"px"; dragging.style.top=parseInt(event.pageY-offsetY.sum())+"px"; return false; } Array.prototype.sum = function() { return (! this.length) ? 0 : this.slice(1).sum() + parseInt(this[0]); }; Array.prototype.in_array = function(el, argStrict) { var key = '', strict = !!argStrict; if (strict) { for (key in this) { if (this[key] === el) { return true; } } } else { for (key in this) { if (this[key] == el) { return true; } } } return false; } |
Часовой пояс GMT +3, время: 20:49. |