Sow nothing reap nothing

jQuery实现简单鼠标点击拖拽网页元素

已有2,980次关注

效果截图:
jQuery鼠标点击拖拽网页元素.gif

html代码:

<div id="show"></div>

css代码:

#show{
    width:100px;
    height:100px;
    position:absolute;
    background:#000;
    text-align:center;
    z-index:999;
    left:500px;
    top:300px;
}

jQuery代码:

$(function(){
    $("#show").mousedown(function(e){
        $(this).css("cursor","move");
        var offset = $(this).offset();
        var x = e.pageX - offset.left;
        var y = e.pageY - offset.top;
        $(document).bind("mousemove",function(ev){
            $("#show").stop();
            var _x = ev.pageX - x;
            var _y = ev.pageY - y;
            $("#show").animate({left:_x+"px",top:_y+"px"},10);
               ev.preventDefault();
        });
    });
    $(document).mouseup(function(){
        $("#show").css("cursor","default");
        $(this).unbind("mousemove");
    });
});

已自动关闭评论