js(jquery)实现鼠标拖动DIV功能

来自:互联网
时间:2020-02-20
阅读:

本文分享一个使用js实现的鼠标拖动div的效果,不同于网上其他的案例,这里实现的是鼠标按在菜单上移动,整个DIV跟着移动的效果。具体细节就不分析了,演示地址,自己看下面的代码吧!

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title></title>
    <script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" type="text/JavaScript" charset="utf-8"></script>
    <style type="text/CSS">
        * {margin: 0;padding: 0;}
        #pic {width: 80px;height: 80px;position: absolute;left: 0;right: 0;border:1px solid #999;width:260px;height:380px;}
        a {border: 1px solid red;}
        #menu{cursor:move;height:50px;background-color:#ccc;border-bottom:1px solid #999;text-align: center;padding-top: 20px;}
    </style>
</head>
<body>
<div id="pic">
    <div id="menu">用鼠标拖动这里可以移动!</div>
</div>
<script type="text/javascript">
    var drag = function (obj, moveObj) {
        obj.bind("mousedown", start);
        function start(event) {
            if (event.button == 0) {
                gapX = event.clientX - obj.offset().left;
                gapY = event.clientY - obj.offset().top;
                $(document).bind("mousemove", move);
                $(document).bind("mouseup", stop);
            }
            return false;
        }
        function move(event) {
            moveObj.css({
                "left": (event.clientX - gapX) + "px",
                "top": (event.clientY - gapY) + "px"
            });
            return false;
        }
        function stop() {
            $(document).unbind("mousemove", move);
            $(document).unbind("mouseup", stop);
        }
    }
    drag($("#menu"), $("#pic"));
</script>
</body>
</html>
返回顶部
顶部