div在屏幕任意位置拖动

div在屏幕任意位置拖动

主要就是三点:

1,获取鼠标按下时的位置;
2,获取鼠标移动后的位置;
3,两者相减就是div的位置;

js代码如下:

// 获取屏幕的高宽度
let cw = $(window).width();
let ch = $(window).height();
// 鼠标按下时获取鼠标在屏幕的位置
$(".box").mousedown(function(e){
    
    
   e = e || window.event;
   // 获取鼠标在元素上的位置(鼠标按下时在元素上得位置)
   let X = e.clientX - $(".box").offset().left;
   let Y = e.clientY  - $(".box").offset().top;

   $(".box").mousemove(function(e){
    
    
       console.log(cw ,ch);
       e = e || window.event;
       let x = e.clientX - X;
       let y = e.clientY - Y;
       if(x<0)x=0;
       if(y<0)y=0;
       if(x + $('.box').width() > cw)  x = cw-$('.box').width();
       if(y +$('.box').height() > ch)  y = ch-$('.box').height();
       $('.box').css({
    
    
           'left':x,
           'top':y
       })
   })
});
// 鼠标抬起事件
$(document).mouseup(function(){
    
    
   $(".box").unbind("mousemove")
})



猜你喜欢

转载自blog.csdn.net/qq_42208679/article/details/103821749