您的位置 >>> 星想互联 >>> 编程技术 >>> JQUERY+JS
制作可拖动的DIV
点击数:278  发布时间2018-02-07 10:45:50
<html>
    <head>
        <title>Dragging</title>
        <style type="text/css">
            .dragMe
            {
                background-color:#8FBC8F;
                height:100px;
                width:100px;
            }
        </style>
    </head>
    <body>
    
        <div class="dragMe">Drag Me</div>
        
        <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function ()
            {
                var mousex = 0, mousey = 0;
                var divLeft, divTop;
                $('.dragMe').mousedown(function(e)
                {
                    var offset = $(this).offset();
                    divLeft = parseInt(offset.left,10);
                    divTop = parseInt(offset.top,10);
                    mousey = e.pageY;
                    mousex = e.pageX;
                    $(this).on('mousemove',dragElement);
                });
 
                function dragElement(event)
                {
                    var left = divLeft + (event.pageX - mousex);
                    var top = divTop + (event.pageY - mousey);
                    $(this).css(
                    {
                        'top' :  top + 'px',
                        'left' : left + 'px',
                        'position' : 'absolute'
                    });
                    return false;
                }
    
                $(document).mouseup(function()
                {
                    $('.dragMe').off('mousemove');
                });
 
            });
        </script>
    </body>
</html>
来源:咸宁网站建设