首頁 > web前端 > js教程 > 主體

js實作滑鼠拖曳功能

巴扎黑
發布: 2017-05-14 14:26:34
原創
1534 人瀏覽過

本文主要介紹了js實作滑鼠拖曳功能的實例程式碼。具有很好的參考價值。下面跟著小編一起來看下吧

效果圖:


###################################### ##########
<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 <style type="text/css">
  #p{
  width: 200px;
  height: 200px;
  background: green;
  position: absolute;
  }
  #p2{
  width: 200px;
  height: 200px;
  background: gold;
  position: absolute;
  top: 200px;
  left: 200px;
  }
 </style>
 </head>
 <body>
 <p id="p">
 </p>
 <p id="p2"></p>
 <script>
  window.onload=function(){
  var p=document.getElementById("p");
  p.onmousedown=function(ev){
   var e=window.event || ev;
   //var Myp=document.getElementById("p");
   //获取到鼠标点击的位置距离p左侧和顶部边框的距离;
   var oX=e.clientX-p.offsetLeft;
   var oY=e.clientY-p.offsetTop;
   //当鼠标移动,把鼠标的偏移量付给p
   document.onmousemove=function(ev){
   //计算出鼠标在XY方向上移动的偏移量,把这个偏移量加给p的左边距和上边距,p就会跟着移动
   var e=window.event|| ev;
   p.style.left=e.clientX-oX+"px";
   p.style.top=e.clientY-oY+"px";
   }
   //当鼠标按键抬起,清除移动事件
   document.onmouseup=function(){
   document.onmousemove=null;
   document.onmouseup=null;
   }
  }
  var p2=document.getElementById("p2");
  p2.onmousedown=function(ev){
   var e=window.event || ev;
   //var Myp=document.getElementById("p");
   //获取到鼠标点击的位置距离p左侧和顶部边框的距离;
   var oX=e.clientX-p2.offsetLeft;
   var oY=e.clientY-p2.offsetTop;
   //当鼠标移动,把鼠标的偏移量付给p
   document.onmousemove=function(ev){
   //计算出鼠标在XY方向上移动的偏移量,把这个偏移量加给p的左边距和上边距,p就会跟着移动
   var e=window.event|| ev;
   p2.style.left=e.clientX-oX+"px";
   p2.style.top=e.clientY-oY+"px";
   }
   //当鼠标按键抬起,清除移动事件
   document.onmouseup=function(){
   document.onmousemove=null;
   document.onmouseup=null;
   }
  }
  }
 </script>
 </body>
</html>
登入後複製

以上是js實作滑鼠拖曳功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!