我需要使一个 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 上,当我快速拖动它时,它不会触发鼠标弹起事件,所以当光标在“容器”内移动时,“ slider ”只是跟随光标,我需要点击某处才能停止。
我没有必要使用 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 中重现可拖动对象粘在鼠标上的问题。以上示例对我来说运行完美。
关于Javascript拖动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29327638/