自己封裝的一個原生JS拖動方法(推薦)
更新時間:2016年11月22日 10:07:56 投稿:jingxian
下面小編就為大家?guī)硪黄约悍庋b的一個原生JS拖動方法(推薦)。小編覺得挺不錯的,希望對大家有所幫助。一起跟隨小編過來看看吧,祝大家游戲愉快哦
代碼:
function drag(t,p){ var point = p || null, target = t || null, resultX = 0, resultY = 0; (!point)? point = target : ''; //如果沒有拖動點,則拖動點默認為整個別拖動元素 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': ''; //重置默認位置。 (resultY >= maxHeight)? target.style.top = maxHeight +'px' : (resultY > 0)?target.style.top = resultY +'px':''; //重置默認位置。 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); //結果值是坐標點減去被拖動元素距離瀏覽器左側的邊距 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(){ // 解決拖動時,當鼠標指向的DOM對象非拖動點元素時,無法觸發(fā)拖動點的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 表示被拖動的元素 * p 表示拖動點 */ // 注意:如果省略拖動點,默認可拖動的區(qū)域是整個被拖動元素
以上就是小編為大家?guī)淼淖约悍庋b的一個原生JS拖動方法(推薦)全部內(nèi)容了,希望大家多多支持腳本之家~
您可能感興趣的文章:
相關文章
JavaScript原型繼承_動力節(jié)點Java學院整理
這篇文章主要為大家詳細介紹了JavaScript原型繼承的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06微信小程序自定義組件的實現(xiàn)方法及自定義組件與頁面間的數(shù)據(jù)傳遞問題
這篇文章主要介紹了微信小程序自定義組件的實現(xiàn)方法及自定義組件與頁面間的數(shù)據(jù)傳遞 ,需要的朋友可以參考下2018-10-10Bootstrap模態(tài)框(Modal)實現(xiàn)過渡效果
這篇文章主要為大家詳細介紹了Bootstrap模態(tài)框(Modal)實現(xiàn)過渡效果的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03Javascript 網(wǎng)頁黑白效果實現(xiàn)代碼(兼容IE/FF等)
今天在網(wǎng)上看到有人推薦的一個不錯的方法,試了一下,效果還是可以的,可以自定義讓網(wǎng)頁的某一部分變成灰度顏色(黑白)。2010-04-04