如何实现鼠标拖动图片功能?jQuery实现代码详解

Admin 2021-04-02 群英技术资讯 829 次浏览

        jQuery如何实现鼠标拖动图片?鼠标拖动图片就与鼠标拖动桌面软件图标差不多,也就是图片的位置随着鼠标的移动位置而改变。这篇文章就通过详细的实例代码给大家介绍一下jQuery如何实现鼠标拖动图片的功能。

首先设一个wrapper,wrapper内的坐标即图片移动的坐标

 #wrapper{
      width: 1000px;
      height:1000px;
      position:relative;
    }

设置图片div,这个div即要拖动的div

#div1{
      position: absolute;
      left:0px;
      top:0px;
      width: 300px;
      height: 200px;
      background: url("d:/Pictures/Earth.jpg");
      background-size:contain;
    }

上面设置了wrapper的定位为relative,div1的定位为absolute。

接下来设计拖动的算法:

思路如下:

1.鼠标点下时让div跟随鼠标移动

2.鼠标松开时停止跟随

首先需要一个函数,他会将该div的坐标改变为当前鼠标的位置:

首先需要定义几个变量,保存当前鼠标的坐标以及图片的坐标

  var timer;
var mouseX=0;
var mouseY=0;
var pic_width = parseInt($("#div1").css("width"));
var pic_height = parseInt($("#div1").css("height"));
$("#wrapper").mousemove(function(e){
mouseX = e.clientX;
mouseY = e.clientY;
});
$("#div1").mousedown(function(){
timer=setInterval(follow,10);
});
$("#div1").mouseup(function(){
clearInterval(timer);
});
var follow = function(){
$("#div1").css("left",mouseX-pic_width/2);
$("#div1").css("top",mouseY-pic_height/2);
};
<!doctype html>
<html>
<head>
<script type = "text/javascript" src = "jquery.js"></script>
<style type = "text/css">
#wrapper{
width: 1000px;
height:1000px;
position: relative;
background: linear-gradient(lightblue,white);
font-size: 40px;
}
#div1{
position: absolute;
left:0px;
top:0px;
width: 300px;
height: 200px;
background: url("d:/Pictures/Earth.jpg");
background-size:contain;
}
</style>
</head>
<body>
<div id = "wrapper">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Impedit numquam accusamus explicabo praesentium laudantium et accusantium, ab ipsum, excepturi necessitatibus quos iste ad qui delenitised debitis reiciendis quam nisi.
</div>
</div>
<script>
var timer;
var mouseX=0;
var mouseY=0;
var pic_width = parseInt($("#div1").css("width"));
var pic_height = parseInt($("#div1").css("height"));
$("#wrapper").mousemove(function(e){
mouseX = e.clientX;
mouseY = e.clientY;
});
$("#div1").mousedown(function(){
timer=setInterval(follow,10);
});
$("#div1").mouseup(function(){
clearInterval(timer);
});
var follow = function(){
$("#div1").css("left",mouseX-pic_width/2);
$("#div1").css("top",mouseY-pic_height/2);
};
</script>
</body>
</html>
<div id = "div1">

那么现在就需要为wrapper添加一个事件监听器,鼠标在wrapper中移动时,修改变量mousex,mousey的值

编写follow函数,并用计时器调用它

完整代码如下所示:

最终效果:

       对于jQuery如何实现鼠标拖动的功能相信大家都有所了解了,希望上述内容对大家学习jQuery知识有所帮助,大家也能够尝试实现一下鼠标拖动图片的功能。


群英智防CDN,智能加速解决方案
标签: jQuery

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

猜你喜欢

成为群英会员,开启智能安全云计算之旅

立即注册
专业资深工程师驻守
7X24小时快速响应
一站式无忧技术支持
免费备案服务
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
在线客服
微信公众号
返回顶部
返回顶部 返回顶部
在线客服
在线客服