Angbike个人博客 > JavaScript/JQuery > jQuery实现简单鼠标点击拖拽网页元素

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

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");
    });
});

效果截图:
1.gif

博客评论已关闭