這篇文章將為大家詳細講解有關js如何實現鼠標拖動功能,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
效果圖:

代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div{
width: 200px;
height: 200px;
background: green;
position: absolute;
}
#div2{
width: 200px;
height: 200px;
background: gold;
position: absolute;
top: 200px;
left: 200px;
}
</style>
</head>
<body>
<div id="div">
</div>
<div id="div2"></div>
<script>
window.onload=function(){
var div=document.getElementById("div");
div.onmousedown=function(ev){
var e=window.event || ev;
//var Mydiv=document.getElementById("div");
//獲取到鼠標點擊的位置距離div左側和頂部邊框的距離;
var oX=e.clientX-div.offsetLeft;
var oY=e.clientY-div.offsetTop;
//當鼠標移動,把鼠標的偏移量付給div
document.onmousemove=function(ev){
//計算出鼠標在XY方向上移動的偏移量,把這個偏移量加給DIV的左邊距和上邊距,div就會跟著移動
var e=window.event|| ev;
div.style.left=e.clientX-oX+"px";
div.style.top=e.clientY-oY+"px";
}
//當鼠標按鍵抬起,清除移動事件
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
}
}
var div2=document.getElementById("div2");
div2.onmousedown=function(ev){
var e=window.event || ev;
//var Mydiv=document.getElementById("div");
//獲取到鼠標點擊的位置距離div左側和頂部邊框的距離;
var oX=e.clientX-div2.offsetLeft;
var oY=e.clientY-div2.offsetTop;
//當鼠標移動,把鼠標的偏移量付給div
document.onmousemove=function(ev){
//計算出鼠標在XY方向上移動的偏移量,把這個偏移量加給DIV的左邊距和上邊距,div就會跟著移動
var e=window.event|| ev;
div2.style.left=e.clientX-oX+"px";
div2.style.top=e.clientY-oY+"px";
}
//當鼠標按鍵抬起,清除移動事件
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
}
}
}
</script>
</body>
</html>關于“js如何實現鼠標拖動功能”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。