使用jQuery使用鼠标水平移动div

时间:2015-08-14 15:06:30

标签: jquery

我试图在鼠标移动时水平移动div。到目前为止,这是我的代码:

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/ 如何使其正常工作?

2 个答案:

答案 0 :(得分:1)

<强> DEMO

&#13;
&#13;
$(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');
    });
});
&#13;
#test {
    width: 300px;
    height: 60px;
    background-color: #333;
    position: absolute;
    top: 0;
    left: 20px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="test"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

为什么只添加差异?您需要相对于位置添加差异。 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');
    });
});