jQuery我想做一个,点击新建出来一个div,鼠标按下拖动div也跟着移动,代码哪里错了

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input id="found" type="button" value="新建">
<span id="aa"></span>
</body>
<script type="text/javascript"src="jquery-2.1.3.min.js"></script>
<script type="text/javascript">
t=true;
$("#found").click(function(){
$("body").append("<div style='width: 200px;height: 200px;background-color:#ccc;position: absolute;' id='run'>按住我移动</div>")
$(this).mouseup(function(){
t=false;
})
$("#run").mousedown (function(e){
$(this).mousemove(function(e){
if(t)
{
$("#aa").html(e.pageX+","+ e.pageY)
$(this).css({"left":e.pageX+5+"px","top":e.pageY+5+"px"})
}
})
})
})

</script>
</html>

你的代码中有以下几处问题:

    t=true;
    $("#found").click(function(){
        $("body").append("<div style='width: 200px;height: 200px;background-color:#ccc;position: absolute;' id='run'>按住我移动</div>")
        
        // 这里的 this 代表 #found 元素,
        // 所以应该改为 $("#run")
        $(this).mouseup(function(){
            // 只要鼠标松开一次,#run 就不能再被拖动了!只能拖动一次吗?
            t=false;
        })
        $("#run").mousedown (function(e){
            // 每次在 #run 上按下鼠标就会添加一次鼠标移动事件!
          $(this).mousemove(function(e){
              if(t)
              {
                  $("#aa").html(e.pageX+","+ e.pageY)
                  // 下面这句应该改为 X、Y 都减 5
                  $(this).css({"left":e.pageX+5+"px","top":e.pageY+5+"px"})
              }
          })
        })
    })


根据你的要求,我写了一段代码,你可以参考一下:

$("#found").click(function(){
    var t=false, x, y;
    $("body").append(
        $("<div style='width: 200px;height: 200px;background-color:#ccc;position: absolute;' id='run'>按住我移动</div>")
        .mouseup(function(){
            t=false;
        }).mousedown (function(e){
            x=e.offsetX;
            y=e.offsetY;
            t=true;
        }).mousemove(function(e){
            if(t)
            {
                $("#aa").html(e.pageX+","+ e.pageY)
                $(this).css({"left":e.pageX-x+"px","top":e.pageY-y+"px"})
            }
        })
    )
})

追问

已经做好了 谢谢

追答

不用谢

温馨提示:答案为网友推荐,仅供参考
相似回答