鼠标拖动文字

本文介绍了一个使用HTML、CSS和JavaScript实现的简单拖动元素案例。案例中包含两个可拖动的正方形,通过监听鼠标事件实现元素在页面上的自由移动。文章详细解释了如何捕捉鼠标点击位置,并跟随鼠标移动更新元素的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!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;//window.event代表着事件对象的状态。只有在事件发生时生效
   //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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值