js拖拽

function drag(cla1,cla2,index){//鼠標可拖拽區域的dom,被拖拽的dom元素,索引 var disX = 0; //鼠標到dom元素左邊距離 var disY = 0; //鼠標到dom元素上邊距離 var oDiv1 = document.getElementsByClassName(cla1)[index]; var oDiv2 = document.getElementsByClassName(cla2)[index]; oDiv1.onmousedown = function(ev){ var ev = ev || window.event; disX = ev.clientX - this.offsetLeft; disY = ev.clientY - this.offsetTop; document.onmousemove = function(ev){ oDiv2.style.left = ev.clientX - disX + 'px'; oDiv2.style.top = ev.clientY - disY + 'px'; if(ev.clientX - disX>=document.body.clientWidth-oDiv2.offsetWidth){ //當拖動dom超過頁面右邊邊界 oDiv2.style.left = document.body.clientWidth-oDiv2.offsetWidth + 'px'; } if(ev.clientX - disX <= 0){ //當拖動dom超過左邊邊界 oDiv2.style.left = 0; } if(ev.clientY - disY>=document.body.clientHeight-oDiv2.offsetHeight){ //當拖動dom超過頁面下邊邊界 oDiv2.style.top = document.body.clientHeight-oDiv2.offsetHeight + 'px'; } if(ev.clientY - disY <= 0){//當拖動dom超過上邊邊界 oDiv2.style.top = 0; } } document.onmouseup = function(ev){ //鼠標擡起移除鼠標move事件 document.onmousemove = null; } } return false;
} var divBox = document.getElementsByClassName('divBox'); for(let i = 0 ; i < divBox.length; i++ ){ drag('divHeader','divBox',i) }
相關文章
相關標籤/搜索