zoukankan      html  css  js  c++  java
  • JavaScript的事件对象_实现拖拽

    实现拖拽一个元素

    拖拽的流程:

    当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown

    当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove

    当鼠标松开时,被拖拽元素固定在当前位置 onmouseup

    <style>
      #box1{
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
      }
    </style>
    <body>
      <div id="box1"></div>
    </body>
    </html>
    <script type="text/javascript">
      window.onload = function(){
        var box1 = document.getElementById("box1");
        //为box1绑定一个鼠标按下事件,当鼠标在被拖拽元素上按下时,开始拖拽  onmousedown
        box1.onmousedown = function(event){
          event = event || window.event;
          //div的偏移量 鼠标.clentX - 元素.offsetLeft
          //div的偏移量 鼠标.clentY - 元素.offsetTop
          var ol = event.clientX - box1.offsetLeft;
          var ot = event.clientY - box1.offsetTop;
          
          //为document绑定一个onmousemove事件
          document.onmousemove = function(event){
            event = event || window.event;
            //当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
            //获取鼠标的坐标
            var left = event.clientX - ol;
            var top = event.clientY - ot;
    
            //修改box1的位置
            box1.style.left = left+"px";
            box1.style.top = top+"px";
          };
    
          //为document绑定一个鼠标松开事件
          document.onmouseup = function(){
            //当鼠标松开时,被拖拽元素固定在当前位置    onmouseup
            //取消document的onmousemove事件
            document.onmousemove = null;
            //取消document的onmouseup事件
            document.onmouseup = null;
          };
        };
      };
    </script>
  • 相关阅读:
    qrcode在手机上不显示的问题
    css 文本溢出省略号
    css解决字段不换行
    vue小程序ref和v-for结合使用得到ref数组的一些问题
    Nginx CORS 跨域资源共享问题
    基于k8s使用helm安装Jenkins
    nginx通过自定义http header 进行服务转发
    基于Kubernetes部署nacos配置中心
    基于Centos 7.8 和Kubeadm部署k8s高可用集群
    Jenkins学习以及配置
  • 原文地址:https://www.cnblogs.com/LO-ME/p/4592598.html
Copyright © 2011-2022 走看看