2015-08-14 2 views
0

Я пытаюсь переместить div горизонтально на перемещение мыши. Вот мой код до сих пор:Переместить div по горизонтали с помощью мыши, используя jQuery

HTML:

<div id="test"></div> 

CSS:

#test { 
    width: 300px; 
    height: 60px; 
    background-color: #333; 
    position: absolute; 
    top: 0; 
    left: 20px; 
} 

JS:

$(document).ready(function(){ 

$('#test').bind('mousedown', function (e) { 
    $(document).bind('mousemove', function (e) { 
     var diff = e.pageX - $('#test').offset().left; 
     $('#test').css('left', diff + 'px'); 
    }); 
}); 

$(window).bind('mouseup', function (e) { 
    $(document).unbind('mousemove'); 
}); 

}); 

Div на самом деле движется, но странным образом. https://jsfiddle.net/ktLskwos/1/ Как я могу заставить его работать правильно?

ответ

1

DEMO

$(document).ready(function(){ 
 
    $('#test').on('mousedown', function (e) { 
 
     $this = $(this); 
 
     $(document).bind('mousemove', function (e) { 
 
      var left = e.pageX - ($this.width()/2); 
 
      var top = e.pageY - ($this.height()/2); 
 
      $('#test').css({ 
 
       'left': left + 'px', 
 
       'top': top + 'px' 
 
      }); 
 
     }); 
 
    }); 
 
    $(window).on('mouseup', function (e) { 
 
     $(document).unbind('mousemove'); 
 
    }); 
 
});
#test { 
 
    width: 300px; 
 
    height: 60px; 
 
    background-color: #333; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 20px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div id="test"></div>

+0

Я удалил «верх»: e.pageY и его то, что мне нужно. Спасибо –

+0

@dchatzis это то, что вы хотели? – RRK

+0

Да, это то, что я хотел, но теперь у меня другая проблема. Я добавил некоторые изображения внутри движущегося div, и теперь он не перемещается, как раньше. https://jsfiddle.net/bj0n7Lnv/ –

0

Почему вы добавляете только разницу? Вам нужно добавить diffrence относительно позиции. Fiddle

$(document).ready(function(){ 
    $('#test').bind('mousedown', function (e) { 
     $(document).bind('mousemove', function (e) { 
      var diff = e.pageX - $('#test').offset().left; 
      $('#test').css('left', (diff+$('#test').offset().left) + 'px'); 
      //You need to remove it the mouse offset plus the diffrence, not to the diffrence between the previous position and the offset- 
      // that'd just leave you rotating left and right between the position you want and the negative, 
      // Since the diffrence changes each time you move on mousedown 
     }); 
    }); 

    $(window).bind('mouseup', function (e) { 
     $(document).unbind('mousemove'); 
    }); 
}); 
+0

Когда я двигаю его, курсор переходит в начало дел. Может ли он остаться там, где я щелкнул и переместил div? –

+0

@dchatzis Это было бы то, что сделал Реджит. –

Смежные вопросы