Home > Web Front-end > JS Tutorial > js implements mouse drag function

js implements mouse drag function

巴扎黑
Release: 2017-05-14 14:26:34
Original
1599 people have browsed it

This article mainly introduces the example code of js to implement mouse dragging function. Has very good reference value. Let’s take a look at it with the editor below

Rendering:

##The code is as follows:


<!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>
Copy after login

The above is the detailed content of js implements mouse drag function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template