为什么这个jq的拖拽只能执行一次呢?求大神帮看一下

HTML代码:

<div></div>

CSS代码:

div{

         width: 100px;

         height: 100px;

         background: red;

         position: absolute;

}

jq代码:

<script type="text/javascript">

     $(function(){

              var disX,disY;

              $("div").mousedown(function(event){

                          /*鼠标距离红方块边缘的距离*/

                          disX=event.pageX - $("div").offset().left;

                          disY=event.pageY - $("div").offset().top;

              });

              $(document).mousemove(function(event){

                      $("div").css({

                      "left":event.pageX - disX,

                      "top":event.pageY - disY

                      });

              });

              $(document).mouseup(function(){

                      $(document).off();

              });

              return false;

     })

 </script>

——————————————————————————————

修改了一下,这样就可以了:

<script type="text/javascript">

         $(function(){

                     var disX,disY;

                     $("div").mousedown(function(event){

                    

                                 disX=event.pageX - $(this).offset().left;

                                 disY=event.pageY - $(this).offset().top;

                                

                                 $(document).mousemove(function(event){

                                                 $("div").css({

                                                         "left":event.pageX - disX ,

                                                         "top":event.pageY - disY

                                                 });

                                 });

                                

                                 $(document).mouseup(function(){

                                                  $(document).off("mousemove");

                                 });

                                

                                 return false;

                    

                     });    

        

         })

</script>


佟舟
浏览 1829回答 2
2回答

anlun214

$(document).off();在你$(document).mouseup的方法里,执行了以上代码,导致document上的事件全部被移除。那么$(document).mousemove和$(document).mouseu全部都被移除了。只剩下可怜的$("div").mousedown存在,当然就不能有第二次了。所以,如果想要做出你要的功能现在的代码结构是不正确的。
打开App,查看更多内容
随时随地看视频慕课网APP