Blogger Information
Blog 61
fans 0
comment 0
visits 54078
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JS拖拽原理
笑颜常开的博客
Original
756 people have browsed it

实例

<!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>
    #ball {
      width: 50px;
      height: 50px;
      background-color: lightpink;
      border-radius: 50%;
      box-shadow: 2px 2px 1px #888;
      position: absolute;
    }
  </style>
</head>

<body>
  <div id="ball"></div>

  <script>
    // onmousedown: 选择, onmouseover: 移动, onmouseup:放下
    //找到小球的位置:
    // 当前鼠标到小球边沿的距离相对是不变的,变得只是小球到左边与顶部的距离
    // 这个不变的距离 ,是鼠标点击下去的一瞬间就确定了,就可以求出来了
    // 根据当前鼠标到当前可视区的距离
    // 求出鼠标当前位置
    var ball = document.getElementById('ball');
    ball.onmousedown = function(event) {
      var x = event.clientX - this.offsetLeft;
      var y = event.clientY - this.offsetTop;
      // console.log(x,y);
      document.onmousemove = function(event) {
        ball.style.left = event.clientX - x + 'px';
        ball.style.top = event.clientY - y + 'px';
      }
      document.onmouseup=function(){
        document.onmousemove=null;
      }
    }
  </script>
</body>

</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post