当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript简单拖拽效果(1)

JavaScript简单拖拽效果(1)

2018年05月01日  | 移动技术网IT编程  | 我要评论

拖拽在前端开发中是很常见的功能,也是基本功之一,本文是不限制范围的拖拽也就是最简单的拖拽,鼠标按下对象,拖拽,松开停止!
1,onmousedown事件
2,onmousemove事件
3,onmouseup事件

因为在按下时拖动,所以onmousemove事件在down后才注册,up事件是用来解绑事件,消除事件!

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>简单拖拽</title>
  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
    }
    #div1 {
      width: 100px;
      height: 100px;
      background: orange;
      position: absolute;
    }
  </style>
</head>
<body style="height: 500000px;">
  <div id="div1"></div>

  <script type="text/javascript">
    function getstyle(obj, attr) {
      if (obj.currentstyle) {
        return obj.currentstyle[attr];
      } else {
        return getcomputedstyle(obj, null)[attr];
      }
    }
    var odiv = document.getelementbyid('div1');
    odiv.onmousedown = function(ev) {
      var oevent = ev || event;
      // var disx = oevent.clientx - odiv.offsetleft;
      // var disy = oevent.clienty - odiv.offsettop;

      var disx = oevent.clientx - parseint(getstyle(odiv, 'left'));
      var disy = oevent.clienty - parseint(getstyle(odiv, 'top'));

      document.onmousemove = function(ev) {
        var oevent = ev || event;
        odiv.style.left = oevent.clientx - disx + 'px';
        odiv.style.top = oevent.clienty - disy + 'px';
      };
      document.onmouseup = function() {
        document.onmousemove = null;
        document.onmouseup = null;
      };
      return false;
    };
  </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网