温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript实现拖拽功能

发布时间:2020-10-13 00:59:34 来源:脚本之家 阅读:280 作者:xiaoba_598 栏目:web开发

本文实例为大家分享了JavaScript实现拖拽功能的具体代码,供大家参考,具体内容如下

盒子拖拽—运用到的有onmousedown事件,onmousemove事件以及onmouseup事件

1、当鼠标点击下去的时候我们需要获取鼠标所在位置的横纵坐标,然后获取盒子的离页面的横纵方向的距离
2、计算出鼠标相对盒子的距离
3、当鼠标移动的时候,获取鼠标移动的距离,在永鼠标此刻的位置减去鼠标相对盒子的距离,获得的是盒子此刻的坐标位置
4、将这个位置赋值给盒子
5、鼠标抬起,清除鼠标移动事件;

代码:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>鼠标拖拽</title>
 <style>
  .box{
   background-color: pink;
   width:200px;
   height:200px;
   border-radius: 50%;
   position: absolute;
   top:20px;
   left:100px;
  }
 </style>
</head>
<body>
 <div class="box">

 </div>
 <script>
  window.onload = function(){
   var box = document.getElementsByClassName('box')[0];
   function drag (ele){
    ele.onmousedown = function(e){
     var e = e || window.event; 
     //此处是为了兼容IE,因为IE中事件对象是作为全局对象( window.event )存在的;
     var pageX = e.pageX || e.clientX + document.documentElement.scrollLeft;
     var pageY = e.pageY || e.clientY + document.documentElement.scrollTop;
     //获取鼠标相对盒子的位置;
     var boxX = pageX - box.offsetLeft;
     var boxY = pageY - box.offsetTop;
     document.onmousemove = function(e){
      var e = e || window.event;
      var pageX = e.pageX || e.clientX + document.documentElement.scrollLeft;
      var pageY = e.pageY || e.clientY + document.documentElement.scrollTop;
      //将鼠标当前的坐标值减去鼠标相对盒子的位置,得到盒子当时的位置并将其赋值给盒子,实现移动效果
      box.style.left = pageX - boxX +'px';
      box.style.top = pageY - boxY + 'px';
     }
    };
    document.onmouseup = function () {
     //清除盒子的移动事件;
     document.onmousemove = null;
    };
   } ;
   drag(box)
  }
 </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI