function drag(t,p){ var point = p || null, target = t || null, resultX = 0, resultY = 0; (!point)? point = target : ''; //如果沒有拖動(dòng)點(diǎn),則拖動(dòng)點(diǎn)默認(rèn)為整個(gè)別拖動(dòng)元素 function getPos(t){ var offsetLeft = 0, offsetTop = 0, offsetParent = t; while(offsetParent){ offsetLeft+=offsetParent.offsetLeft; offsetTop+=offsetParent.offsetTop; offsetParent = offsetParent.offsetParent; } return {'top':offsetTop,'left':offsetLeft}; } function core(){ var width = document.body.clientWidth || document.documentElement.clientWidth, height = document.body.clientHeight || document.documentElement.clientHeight; maxWidth = width - target.offsetWidth, maxHeight = height - target.offsetHeight; (resultX >= maxWidth)? target.style.left = maxWidth+'px' : (resultX > 0)?target.style.left = resultX +'px': ''; //重置默認(rèn)位置。 (resultY >= maxHeight)? target.style.top = maxHeight +'px' : (resultY > 0)?target.style.top = resultY +'px':''; //重置默認(rèn)位置。 point.onmousedown=function(e){ var e = e || window.event, coordX = e.clientX, coordY = e.clientY, posX = getPos(target).left, posY = getPos(target).top; point.setCapture && point.setCapture(); //將Mouse事件鎖定到指定元素上。 document.onmousemove=function(e){ var ev = e || window.event, moveX = ev.clientX, moveY = ev.clientY; resultX = moveX - (coordX - posX); //結(jié)果值是坐標(biāo)點(diǎn)減去被拖動(dòng)元素距離瀏覽器左側(cè)的邊距 resultY = moveY - (coordY - posY); (resultX > 0 )?((resultX < maxWidth)?target.style.left = resultX+'px' : target.style.left = maxWidth+'px') : target.style.left = '0px'; (resultY > 0 )?((resultY < maxHeight)?target.style.top = resultY+'px' : target.style.top = maxHeight+'px') : target.style.top = '0px'; ev.stopPropagation && ev.stopPropagation(); ev.preventDefault; ev.returnValue = false; ev.cancelBubble = true; }; }; document.onmouseup=function(){ // 解決拖動(dòng)時(shí),當(dāng)鼠標(biāo)指向的DOM對(duì)象非拖動(dòng)點(diǎn)元素時(shí),無法觸發(fā)拖動(dòng)點(diǎn)的onmousedown的BUG。 document.onmousemove = null; point.releaseCapture && point.releaseCapture(); // 將Mouse事件從指定元素上移除。 }; point.onmouseup=function(e){ var e = e || window.event; document.onmousemove = null; point.releaseCapture && point.releaseCapture(); }; } core(); window.onresize = core; }
使用方式:
drag(t,p) /* * 說明 * t 表示被拖動(dòng)的元素 * p 表示拖動(dòng)點(diǎn) */ // 注意:如果省略拖動(dòng)點(diǎn),默認(rèn)可拖動(dòng)的區(qū)域是整個(gè)被拖動(dòng)元素
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com