jquery实现拖动效果(代码+解释)

1.代码效果

当鼠标点击目标区域并且移动可以实现在网页的窗口内移动,鼠标松开之后停止。

2.代码及解释

详细解释在代码下部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.5.0.min.js"></script>
    <style>
        *{margin: 0px;padding: 0px;}
        #hid{
            width: 200px;
            height: 200px;
            background-color: aqua;
            cursor: move;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="hid"></div>
</body>
    <script>
        $(function(){
            $("#hid").mousedown(function(e){
                //发生点击事件时修改颜色为红色
                $(this).css("background-color","red");
                //获取div层的位置
                var offset = $(this).offset();
                //x为点击的位置距离div的左侧的距离
                var x = e.pageX - offset.left;
                //距离div的顶部的距离
                var y = e.pageY - offset.top;
                //绑定鼠标移动时间
                $(document).on("mousemove",function(en){
                    $("#hid").css({left:en.pageX-x+"px",top:en.pageY-y+"px"});
                });
            }).mouseup(function(){
                //颜色恢复为原来颜色
                $(this).css("background-color","aqua");
                //取消事件
                $(document).off("mousemove");
            })
        });
    </script>
</html>

1.pageX和offset.left的的区别
pageX是鼠标的点击位置距离页面左边的距离。
offset.left是鼠标点击的div层的左侧距离页面左侧的距离。

在这里插入图片描述
2.鼠标的移动事件绑定使用的是.on
这里使用.on绑定方便使用.off取消事件

猜你喜欢

转载自blog.csdn.net/apple_51491580/article/details/113851194