• JS拖拽pro


     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Document</title>
     6 <style>
     7     *{
     8         margin:0;
     9         padding:0;
    10     }
    11     img{
    12         width:100%;
    13         height: 100%;
    14     }
    15     .div1{
    16         width: 100px;
    17         height: 100px;
    18         position: absolute;
    19     }
    20     .box{
    21         opacity: .4;
    22         filter:alpha(opacity=40);
    23     }
    24 </style>
    25 <script>
    26 window.onload=function(){
    27     var oDiv=document.getElementById('div1');
    28     oDiv.onmousedown=function(ev){
    29         var ev=ev||event;
    30         var disX=ev.clientX-oDiv.offsetLeft;
    31         var disY=ev.clientY-oDiv.offsetTop;
    32         var oNewD=oDiv.cloneNode(true);
    33         oNewD.removeAttribute('id');
    34         oNewD.className+=' box';
    35         oDiv.parentNode.appendChild(oNewD);
    36         document.onmousemove=function(ev){
    37             var ev=ev||event;
    38             var cW=document.documentElement.clientWidth;
    39             var cH=document.documentElement.clientHeight;
    40             var l=ev.clientX-disX;
    41             var t=ev.clientY-disY;
    42             if(l<50){
    43                 l=0;
    44             }else if(l>cW-oDiv.offsetWidth-50){
    45                 l=cW-oDiv.offsetWidth;
    46             }
    47             if(t<50){
    48                 t=0;
    49             }else if(t>cH-oDiv.offsetHeight-50){
    50                 t=cH-oDiv.offsetHeight;
    51             }
    52             oNewD.style.left=l+'px';
    53             oNewD.style.top=t+'px';
    54         };
    55         document.onmouseup=function(){
    56             oDiv.style.left=oNewD.style.left;
    57             oDiv.style.top=oNewD.style.top;
    58             oDiv.parentNode.removeChild(oNewD);
    59             document.onmouseup=document.onmousemove=null;
    60             oDiv.releaseCapture&&oDiv.releaseCapture();
    61         };
    62         oDiv.setCapture&&oDiv.setCapture();
    63         return false;
    64     };
    65 };
    66 </script>
    67 </head>
    68 <body>
    69     <div id="div1" class="div1">
    70         <img src="img/m1.jpg" alt="">
    71     </div>
    72 </body>
    73 </html>

    拖拽的第一步就是用disX和disY存位置,存的是鼠标和元素的距离,然后通过鼠标移动的距离来相应改变对象的位置就可以了。

  • 相关阅读:
    降低大气分
    99999
    88888
    77777
    HandlerThread实现原理
    Android 内存泄漏总结
    Handler实现机制,同步屏障,IdleHandler
    launcher 配置
    微信小程序 上传图片七牛
    微信小程序 跳转传参数 传对象
  • 原文地址:https://www.cnblogs.com/yty12345/p/5289515.html
Copyright © 2020-2023  润新知