很多時候我們做網站都會遇到 JS拖拽的需求,今天就按照一個彈出框拖拽作為一個小案例寫個JS原生的代碼。

按照上面的需求咱們開始制作一個拖拽效果吧。
第一步、咱們得寫一個布局和響應的css
<div id="box"> <div id="btn">標題</div> <p>青格勒前端博客!</p> <p>www.cenggel.com</p></div>
<style>
#box{ height:200px; width:200px; background:#999; position:absolute;} #btn{ height:30px; background:#000; cursor:all-scroll; padding:0 10px; color:#fff;}</style>
這里的話咱們id=btn的為拖拽的區域。
二、邏輯講述
整個JS代碼不是很多,當鼠標按下的時候獲取鼠標的位置和id=box的上距和左邊距,然后計算目前的位置。
然后這時候鼠標移動的時候再次計算鼠標的位置,然后給id=box位置
當鼠標按鈕松開的時候把onmousemove和onmouseup清除掉
三、JS代碼部分
<script type="text/javascript">
function drag(obtnf,obtn){ //按鈕及初始值
var obtn = document.getElementById(obtn),
obtnf = document.getElementById(obtnf),
disX = 0,
disY = 0; //鼠標按下時開始計算
obtn.onmousedown = function(ev){ var ev = ev || window.event;
disX = ev.clientX - obtnf.offsetLeft;
disY = ev.clientY - obtnf.offsetTop; //鼠標按下并移動時計算
document.onmousemove = function(ev){ var ev = ev || window.event;
obtnf.style.left = ev.clientX - disX + 'px';
obtnf.style.top = ev.clientY - disY + 'px';
}; //鼠標松開時清除時間
document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null;
}; return false;
};
}; //引用
drag("box","btn")</script> www.gendan5.com
最后咱們的效果如下

做到這里其實咱們的效果并不完美,應為當我們拖拽的時候發現,他能直接被拖到瀏覽器的外面去了,所以咱們再給他加點限制。
最終JS代碼如下:
<script type="text/javascript">
function xianzhi(val,max,min){ if (val > max){ return max;
}else if(val < min){ return min;
}else{ return val;
} console.log(val)
} function drag(obtnf,obtn){ //按鈕及初始值
var obtn = document.getElementById(obtn),
obtnf = document.getElementById(obtnf),
disX = 0,
disY = 0; //鼠標按下時開始計算
obtn.onmousedown = function(ev){ var ev = ev || window.event;
disX = ev.clientX - obtnf.offsetLeft;
disY = ev.clientY - obtnf.offsetTop; //鼠標按下并移動時計算
document.onmousemove = function(ev){ var ev = ev || window.event; var lefts= (ev.clientX - disX),
tops= (ev.clientY - disY),
maxle= (document.documentElement.clientWidth - obtnf.offsetWidth),
maxto= (document.documentElement.clientHeight - obtnf.offsetHeight)
lefts = xianzhi(lefts,maxle,0)
tops = xianzhi(tops,maxto,0)
obtnf.style.left = lefts + 'px';
obtnf.style.top = tops + 'px';
}; //鼠標松開時清除時間
document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null;
}; return false;
};
}; //引用
drag("box","btn")
做到這里一個小型的拖拽效果就出來了。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。