Javascript拖动对象

Javascript dragging object

本文关键字:对象 拖动 Javascript      更新时间:2023-09-26

我需要使一个div可拖动,并根据鼠标位置设置它的左侧位置。我已经搜索了一点,这就是我到目前为止所拥有的:

container = $('<div></div>').appendTo($('body')).addClass('container');
someText = $('<div>Some text</div>').appendTo(container);
slider = $('<div></div>').appendTo(container);
slider.addClass('slider');
var isDragging = false;
slider.on('mousedown', function () {
    isDragging = true;
});
$(window).on('mouseup', function () {
    console.log('mouseup');
    isDragging = false;
});
container.on('mouseleave', function () {
    console.log('mouseleave');
    isDragging = false;
});
container.on('mousemove', function (e) {
    if (isDragging) {
        var newLeft = parseInt((e.pageX - container.offset().left), 10);
        console.log(newLeft);
        slider.css('left', newLeft);
    }
});

http://jsfiddle.net/w9gxxuvw/2/

白色盒子应该是可以拖动的,但也有一些缺点。首先,当我向下拖动LPM时,我选择上面的文本。其次,在chrome上,当我快速拖动它时,它不会触发鼠标向上事件,所以当光标在"容器"内移动时,"滑块"只会跟随光标,我需要点击某个地方停止。

我没有必要使用jQuery,但我不想使用另一个大框架或jQuery插件。

您可以使用user-select CSS属性阻止文本选择:

container = $('<div></div>').appendTo($('body')).addClass('container');
someText = $('<div>Some text</div>').appendTo(container);
slider = $('<div></div>').appendTo(container);
slider.addClass('slider');
var isDragging = false;
slider.on('mousedown', function () {
  isDragging = true;
});
$(window).on('mouseup', function () {
  isDragging = false;
});
container.on('mouseleave', function () {
  isDragging = false;
});
container.on('mousemove', function (e) {
  if (isDragging) {
    var newLeft = parseInt((e.pageX - container.offset().left), 10);
    slider.css('left', newLeft);
  }
});
.container {
    display:block;
    width:400px;
    height:100px;
    background: red;
    -moz-user-select: none;
    -ms-user-select: none;
    -webkit-user-select: none;
    user-select: none;
}
.slider {
    display:block;
    width:10px;
    height:10px;
    background: #fff;
    position:relative;
    left: 0%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我无法在Chrome 42、Firefox 36或Safari 7中重现拖动鼠标的问题。上面的例子对我来说运行得很完美。

阻止脚本中文本选择的默认操作似乎更合乎逻辑,它也比CSS user-select有更深的支持。由于(大多数)事件都是在这个函数中连接的,所以我会嵌套它们。这将允许进行一些优化。解除mousemove的绑定也是有意义的,在几次事件之后,您通常会开始注意到迟缓的行为。

...
container.on('mousedown', function(e) {
e.preventDefault();
});
slider.on('mousedown', function() {
$(window).one('mouseup', function() {
console.log('mouseup');
container.off('mousemove');
});
container.on('mousemove', function(e) {
var newLeft = Math.round(e.pageX-container.offset().left);
console.log(newLeft);
slider.css('left', newLeft);
})
.one('mouseleave', function() {
console.log('mouseleave');
container.off('mousemove');
});
});

http://jsfiddle.net/w9gxxuvw/8/